注解对比
@Component @Bean 区别
-
@Component @Bean 区别
-
@Component注解表明一个类会作为组件类,并告知Spring要为这个类创建bean。
-
@Bean注解告诉Spring这个方法将会返回一个对象,这个对象要注册为Spring应用上下文中的bean。通常方法体中包含了最终产生bean实例的逻辑。
两者的目的是一样的,都是注册bean到Spring容器中。
区别:
-
@Component(@Controller、@Service、@Repository)通常是通过类路径扫描来自动侦测以及自动装配到Spring容器中。
-
@Bean注解通常是我们在标有该注解的方法中定义产生这个bean的逻辑。
-
@Component 作用于类,@Bean作用于方法。
-
@Component和@Configuration
-
@Component和@Configuration作为配置类的差别
@Component注解的范围最广,所有类都可以注解
@Configuration注解一般注解在这样的类上:这个类里面有@Value注解的成员变量和@Bean注解的方法,就是一个配置类。
-
@Configuration标记的类必须符合下面的要求:
配置类必须以类的形式提供(不能是工厂方法返回的实例),允许通过生成子类在运行时增强(cglib 动态代理)。(对bean方法进行增强)
配置类不能是 final 类(没法动态代理)。
配置注解通常为了通过 @Bean 注解生成 Spring 容器管理的类,
配置类必须是非本地的(即不能在方法中声明,不能是 private)。
任何嵌套配置类都必须声明为static。
@Bean 方法可能不会反过来创建进一步的配置类(也就是返回的 bean 如果带有 @Configuration,也不会被特殊处理,只会作为普通的 bean)。加载过程
Spring 容器在启动时,会加载默认的一些PostPRocessor,其中就有ConfigurationClassPostProcessor,这个后置处理程序专门处理带有@Configuration注解的类,这个程序会在bean 定义加载完成后,在bean初始化前进行处理。主要处理的过程就是使用cglib动态代理增强类,而且是对其中带有@Bean注解的方法进行处理。
@Component和@Configuration都可以声明Spring bean
@Component public class Configuration { @Bean public UserService userService() { return new UserService(); } } @org.springframework.context.annotation.Configuration public class Configuration { @Bean public UserService userService() { return new UserService(); } }
区别:
第一段代码会像我们期望的一样正常运行,因为new SimpleBeanConsumer(simpleBean())这段代码中simpleBean()方法会由Spring代理执行,Spring发现方法所请求的Bean已经在容器中,那么就直接返回容器中的Bean。所以全局只有一个SimpleBean对象的实例。
第二段代码在执行new SimpleBeanConsumer(simpleBean()) 时simpleBean()不会被Spring代理,会直接调用simpleBean()方法获取一个全新的SimpleBean对象实例所以全局会有多个SimpleBean对象的实
使用Configuration时在driver和spring容器之中的是同一个对象,而使用Component时是不同的对象。
https://blog.youkuaiyun.com/baidu_41634343/article/details/95176401