騰訊二面:@Bean 與 @Component 用在同一個類上,會怎麼樣?

來源:cnblogs.com/youzhibing/p/15354706.html

疑慮背景

疑慮描述

最近,在進行開發的過程中,發現之前的一個寫法,類似如下:

以我的理解,@Configuration 加 @Bean 會創建一個 userName 不爲 null 的 UserManager 對象,而 @Component 也會創建一個 userName 爲 null 的 UserManager 對象。

那麼我們在其他對象中注入 UserManager 對象時,到底注入的是哪個對象?

因爲項目已經上線了很長一段時間了,所以這種寫法沒有編譯報錯,運行也沒有出問題。後面去找同事瞭解下,實際是想讓:

生效,而實際也確實是它生效了。那麼問題來了:Spring 容器中到底有幾個 UserManager 類型的對象?

Spring Boot 版本

項目中用的 Spring Boot 版本是:2.0.3.RELEASE。對象的 scope 是默認值,也就是 singleton。

Spring Boot 基礎就不介紹了,推薦下這個實戰教程:

https://github.com/javastacks/spring-boot-best-practice

結果驗證

驗證方式有很多,可以 debug 跟源碼,看看 Spring 容器中到底有幾個 UserManager 對象,也可以直接從 UserManager 構造方法下手,看看哪幾個構造方法被調用,等等。

我們從構造方法下手,看看 UserManager 到底實例化了幾次。

只有有參構造方法被調用了,無參構造方法巋然不動(根本沒被調用)。如果想了解的更深一點,可以讀讀:Spring 的循環依賴,源碼詳細分析 → 真的非要三級緩存嗎?

https://www.cnblogs.com/youzhibing/p/14337244.html

既然 UserManager 構造方法只被調用了一次,那麼前面的問題:到底注入的是哪個對象。答案也就清晰了,沒得選了呀,只能是 @Configuration 加 @Bean 創建的 userName 不爲 null 的 UserManager 對象。

問題又來了:爲什麼不是 @Component 創建的 userName 爲 null 的 UserManager 對象?

源碼解析

@Configuration 與 @Component 關係很緊密。

所以@Configuration能夠被component scan。

其中 ConfigurationClassPostProcessor與@Configuration 息息相關,其類繼承結構圖如下:

它實現了BeanFactoryPostProcessor接口和PriorityOrdered接口。

關於 BeanFactoryPostProcessor,可以看看:

https://www.cnblogs.com/youzhibing/p/10559337.html

從AbstractApplicationContext的refresh方法調用的invokeBeanFactoryPostProcessors(beanFactory)開始,來跟下源碼。

此時完成了com.lee.qsl包下的component scan ,com.lee.qsl包及子包下的 UserConfig、UserController和UserManager都被掃描出來。注意,此刻@Bean的處理還未開始,UserManager是通過@Component而被掃描出來的;此時Spring容器中beanDefinitionMap中的 UserManager是這樣的。

接下來一步很重要,與我們想要的答案息息相關。

循環遞歸處理UserConfig 、UserController和UserManager,把它們都封裝成 ConfigurationClass ,遞歸掃描 BeanDefinition。循環完之後,我們來看看 configClasses。

UserConfig bean定義中beanMethods中有一個元素 [BeanMethod:name=userManager,declaringClass=com.lee.qsl.config.UserConfig]。

然後我們接着往下走,來仔細看看答案出現的環節。

是不是有什麼發現?@Component修飾的UserManager定義直接被覆蓋成了@Configuration +@Bean修飾的UserManager定義。Bean定義類型也由ScannedGenericBeanDefinition替換成了ConfigurationClassBeanDefinition。

後續通過BeanDefinition創建實例的時候,創建的自然就是@Configuration+@Bean修飾的 UserManager,也就是會反射調用UserManager的有參構造方法。

自此,答案也就清楚了。Spring 其實給出了提示:

2021-10-03 20:37:33.697  INFO 13600 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'userManager' with a different definition: replacing [Generic bean: class [com.lee.qsl.manager.UserManager]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [D:\qsl-project\spring-boot-bean-component\target\classes\com\lee\qsl\manager\UserManager.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=userConfig; factoryMethodName=userManager; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/lee/qsl/config/UserConfig.class]]

只是日誌級別是 info ,太不顯眼了。

Spring升級優化

可能Spring團隊意識到了info級別太不顯眼的問題,或者說意識到了直接覆蓋的處理方式不太合理。所以在Spring 5.1.2.RELEASE (Spring Boot 則是 2.1.0.RELEASE )做出了優化處理。

推薦一個 Spring Boot 基礎教程及實戰示例:

https://github.com/javastacks/spring-boot-best-practice

我們來具體看看。

啓動直接報錯,Spring也給出了提示。

The bean 'userManager', defined in class path resource [com/lee/qsl/config/UserConfig.class], could not be registered. A bean with that name has already been defined in file [D:\qsl-project\spring-boot-bean-component\target\classes\com\lee\qsl\manager\UserManager.class] and overriding is disabled.

我們來跟下源碼,主要看看與Spring 5.0.7.RELEASE的區別。

新增了配置項allowBeanDefinitionOverriding來控制是否允許BeanDefinition覆蓋,默認情況下是不允許的。我們可以在配置文件中配置:spring.main.allow-bean-definition-overriding=true ,允許BeanDefinition覆蓋。這種處理方式是更優的,將選擇權交給開發人員,而不是自己偷偷的處理,已達到開發者想要的效果。

總 結

Spring 5.0.7.RELEASE ( Spring Boot 2.0.3.RELEASE )支持@Configuration+ @Bean與@Component同時作用於同一個類。啓動時會給info級別的日誌提示,同時會將@Configuration+@Bean修飾的 BeanDefinition覆蓋掉@Component修飾的BeanDefinition。

也許Spring團隊意識到了上述處理不太合適,於是在Spring 5.1.2.RELEASE做出了優化處理。增加了配置項:allowBeanDefinitionOverriding,將主動權交給了開發者,由開發者自己決定是否允許覆蓋。

補充

關於allowBeanDefinitionOverriding,前面有誤,特意去翻了下源碼,補充如下。Spring 1.2引進DefaultListableBeanFactory的時候就有了private boolean allowBeanDefinitionOverriding=true;,默認是允許BeanDefinition覆蓋。

Spring4.1.2引進isAllowBeanDefinitionOverriding()方法。

Spring自始至終默認都是允許BeanDefinition覆蓋的,變的是Spring Boot ,Spring Boot 2.1.0之前沒有覆蓋Spring 的allowBeanDefinitionOverriding默認值,仍是允許BeanDefinition覆蓋的。

Spring Boot 2.1.0中SpringApplication定義了私有屬性:allowBeanDefinitionOverriding。

沒有顯示的指定值,那麼默認值就是false ,之後在Spring Boot啓動過程中,會用此值覆蓋掉Spring中的allowBeanDefinitionOverriding的默認值。

關於allowBeanDefinitionOverriding,我想大家應該已經清楚了。

近期熱文推薦:

1.1,000+ 道 Java面試題及答案整理(2022最新版)

2.勁爆!Java 協程要來了。。。

3.Spring Boot 2.x 教程,太全了!

4.別再寫滿屏的爆爆爆炸類了,試試裝飾器模式,這纔是優雅的方式!!

5.《Java開發手冊(嵩山版)》最新發布,速速下載!

覺得不錯,別忘了隨手點贊+轉發哦!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章