關(guān)于Spring @Bean 相同加載順序不同結(jié)果不同的問題記錄
問題說明
兩個全注解類
LocalConfig1
@Configuration
public class LocalConfig1 {
public LocalConfig1(){
System.out.println("LocalConfig1()");
}
@Bean(name = "x1")
public X x() {
System.out.println("start new X 1");
return new X("xName");
}
}LocalConfig2
@Configuration
public class LocalConfig2 {
public LocalConfig2(){
System.out.println("LocalConfig2()");
}
@Bean(name = "x1")
public X x() {
System.out.println("start new X 2");
return new X();
}
@Bean
public Y y() {
System.out.println("start new Y");
return new Y();
}
}對于@Bean X類型的使用了不同的構(gòu)造函數(shù)
public class X {
private String xName;
@Autowired
private Y y;
public X() {
System.out.println("X()");
}
public X(String xName) {
this.xName = xName;
}
public void sy(){
System.out.println("y:" + y);
}
public void sayMyName(){
System.out.println("xName:" + xName);
}
}測試輸出1

測試輸出2

即不同的順序?qū)е铝私Y(jié)果的不同
@Bean注解的BeanDefinition加入時機(jī)
回顧:https://doctording.blog.csdn.net/article/details/144865082 & https://doctording.blog.csdn.net/article/details/144868096 中的知識:
使用new AnnotationConfigApplicationContext后會默認(rèn)加入ConfigurationClassPostProcessor的beanDefinition,并在refresh()方法中的invokeBeanFactoryPostProcessors(beanFactory);完成實(shí)例化,即得到ConfigurationClassPostProcessor,然后執(zhí)行其 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); 方法
因?yàn)镃onfigurationClassPostProcessor是一個BeanDefinitionRegistryPostProcessor

在執(zhí)行過程中會判斷全注解類

然后繼續(xù)從全注解類中加載可能的bean

從LocalConfig1中可以讀到@Bean注解方法,然后添加BeanDefintion

從LocalConfig2中可以也讀到@Bean注解方法,然后添加BeanDefintion; 其中相同的BeanName直接覆蓋了,如下圖:

所以看全注解加載順序,取了最后那個beanDefinition, 所以出現(xiàn)了了測試現(xiàn)象。
總結(jié)
本例是在spring 5.1.3.RELEASE版本下的測試,探究了存在不同全注解類有相同的@Bean的情況,加載順序不同導(dǎo)致的最后Bean實(shí)例不同。工作中應(yīng)該避免這種寫法,同時也要注意自身Spring版本用到了是否有此邏輯
到此這篇關(guān)于關(guān)于Spring @Bean 相同加載順序不同結(jié)果不同的問題記錄的文章就介紹到這了,更多相關(guān)Spring @Bean 加載順序內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
在spring?boot3中使用native?image的最新方法
這篇文章主要介紹了在spring?boot3中使用native?image?,今天我們用具體的例子來給大家演示一下如何正確的將spring boot3的應(yīng)用編譯成為native image,需要的朋友可以參考下2023-01-01
springboot CompletableFuture異步線程池詳解
這篇文章主要介紹了springboot CompletableFuture異步線程池的使用,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-04-04
Spring 動態(tài)代理實(shí)現(xiàn)代碼實(shí)例
這篇文章主要介紹了Spring 動態(tài)代理實(shí)現(xiàn)代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-09-09

