@Configuration注解的類:
/** * @Description 測(cè)試用的配置類 * @Author 弟中弟 * @CreateTime 2019/6/18 14:35 */ @Configuration public class MyBeanConfig { @Bean public Country country(){ return new Country(); } @Bean public UserInfo userInfo(){ return new UserInfo(country()); } }
@Component注解的類:
/** * @Description 測(cè)試用的配置類 * @Author 弟中弟 * @CreateTime 2019/6/18 14:36 */ @Component public class MyBeanConfig { @Bean public Country country(){ return new Country(); } @Bean public UserInfo userInfo(){ return new UserInfo(country()); } }
測(cè)試:
@RunWith(SpringRunner.class) @SpringBootTest public class DemoTest { @Autowired private Country country; @Autowired private UserInfo userInfo; @Test public void myTest() { boolean result = userInfo.getCountry() == country; System.out.println(result ? "同一個(gè)country" : "不同的country"); } }
如果是@Configuration打印出來(lái)的則是同一個(gè)country,@Component則是不同的country,這是為什么呢?
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface Configuration { @AliasFor( annotation = Component.class ) String value() default ""; }
你點(diǎn)開@Configuration會(huì)發(fā)現(xiàn)其實(shí)他也是被@Component修飾的,因此context:component-scan/ 或者 @ComponentScan都能處理@Configuration注解的類。
@Configuration標(biāo)記的類必須符合下面的要求:
配置類必須以類的形式提供(不能是工廠方法返回的實(shí)例),允許通過(guò)生成子類在運(yùn)行時(shí)增強(qiáng)(cglib 動(dòng)態(tài)代理)。
配置類不能是 final 類(沒(méi)法動(dòng)態(tài)代理)。
配置注解通常為了通過(guò) @Bean 注解生成 Spring 容器管理的類,
配置類必須是非本地的(即不能在方法中聲明,不能是 private)。
任何嵌套配置類都必須聲明為static。
@Bean 方法可能不會(huì)反過(guò)來(lái)創(chuàng)建進(jìn)一步的配置類(也就是返回的 bean 如果帶有
@Configuration,也不會(huì)被特殊處理,只會(huì)作為普通的 bean)。
但是spring容器在啟動(dòng)時(shí)有個(gè)專門處理@Configuration的類,會(huì)對(duì)@Configuration修飾的類cglib動(dòng)態(tài)代理進(jìn)行增強(qiáng),這也是@Configuration為什么需要符合上面的要求中的部分原因,那具體會(huì)增強(qiáng)什么呢?
這里是個(gè)人整理的思路 如果有錯(cuò)請(qǐng)指點(diǎn)
userInfo()中調(diào)用了country(),因?yàn)槭欠椒潜厝籧ountry()生成新的new contry(),所以動(dòng)態(tài)代理增加就會(huì)對(duì)其進(jìn)行判斷如果userInfo中調(diào)用的方法還有@Bean修飾,那就會(huì)直接調(diào)用spring容器中的country實(shí)例,不再調(diào)用country(),那必然是一個(gè)對(duì)象了,因?yàn)閟pring容器中的bean默認(rèn)是單例。不理解比如xml配置的bean
<bean id="country" class="com.hhh.demo.Country" scope="singleton"/>
這里scope默認(rèn)是單例。
以上是個(gè)人理解,詳情源碼的分析請(qǐng)看http://www.ythuaji.com.cn/article/4572.html
但是如果我就想用@Component,那沒(méi)有@Component的類沒(méi)有動(dòng)態(tài)代理咋辦呢?
/** * @Description 測(cè)試用的配置類 * @Author 弟中弟 * @CreateTime 2019/6/18 14:36 */ @Component public class MyBeanConfig { @Autowired private Country country; @Bean public Country country(){ return new Country(); } @Bean public UserInfo userInfo(){ return new UserInfo(country); } }
這樣就保證是同一個(gè)Country實(shí)例了
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。