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