美文网首页我爱编程
2018-06-21-@Configuration @Bean

2018-06-21-@Configuration @Bean

作者: 迪奥炸 | 来源:发表于2018-06-21 17:24 被阅读0次

https://blog.csdn.net/u012260707/article/details/52021265

https://segmentfault.com/a/1190000014119872

如何将生命周期交给Spring IoC 容器

一\注册Bean

1、使用自动配置的方式   用@Controller、@Service...+扫描器

2、使用JavaConfig的方式,  用@Configuration+@Bean

3、使用XML配置的方式

@Component and @Bean do two quite different things, and shouldn't be confused.

@Component (and @Service and @Repository) are used to auto-detect and auto-configure beans using classpath scanning. There's an implicit one-to-one mapping between the annotated class and the bean (i.e. one bean per class). Control of wiring is quite limited with this approach, since it's purely declarative.

@Bean is used to explicitly declare a single bean, rather than letting Spring do it automatically as above. It decouples the declaration of the bean from the class definition, and lets you create and configure beans exactly how you choose.

@Configuration可理解为 异形的@Component[可以看一下它的组成],@Configuration其实就是告诉Spring, Spring容器要怎么配置(怎么注册Bean,怎么装配Bean),类似XML中的<Beans>

@Bean就是我要获取这个Bean地时候,Spring要按照我在Configuration的方式获得bean,类似XML中的<Bean>

用@Bean注解的方法, 会实例化\配置\并初始化一个新的对象,这个对象会由Spring IoC容器管理

bean地生命周期:Singleton Bean完成这些在容器启动时:读取类定义 -> 调用构造函数实例化 -> 填充属性值 -> 初始化

springboot自带扫描注解,

如果只有Spring时,需要手动配置注解扫描器<context:component-scan base-package="com.xxx.xxx" />

在@Component注释的类中不能定义 类内依赖的@Bean注解的方法.  @Configuration可以

二\装配Bean

通过以上方法将类添加到 SpringIoC 容器中后,通过@AutoWired注解去装配Bean

相关文章

网友评论

    本文标题:2018-06-21-@Configuration @Bean

    本文链接:https://www.haomeiwen.com/subject/mhzqyftx.html