国产成人精品久久免费动漫-国产成人精品天堂-国产成人精品区在线观看-国产成人精品日本-a级毛片无码免费真人-a级毛片毛片免费观看久潮喷

您的位置:首頁技術(shù)文章
文章詳情頁

springboot static關(guān)鍵字真能提高Bean的優(yōu)先級(厲害了)

瀏覽:26日期:2023-08-26 08:08:41

生命太短暫,不要去做一些根本沒有人想要的東西。本文已被 https://www.yourbatman.cn 收錄,里面一并有Spring技術(shù)棧、MyBatis、JVM、中間件等小而美的專欄供以免費學習。關(guān)注公眾號【BAT的烏托邦】逐個擊破,深入掌握,拒絕淺嘗輒止。

springboot static關(guān)鍵字真能提高Bean的優(yōu)先級(厲害了)

前言

各位小伙伴大家好,我是A哥。關(guān)于Spring初始化Bean的順序問題,是個老生常談的話題了,結(jié)論可總結(jié)為一句話:全局無序,局部有序。Spring Bean整體上是無序的,而現(xiàn)實是大多數(shù)情況下我們真的無需關(guān)心,無序就無序唄,無所謂嘍。但是(此處應(yīng)該有但是哈),我有理由相信,對于有一定從業(yè)經(jīng)驗的Javaer來說,或多或少都經(jīng)歷過Bean初始化順序帶來的“困擾”,也許是因為沒有對你的功能造成影響,也許可能是你全然“不知情”,所以最終就不了了之~

隱患終歸隱患,依照墨菲定律來講,擔心的事它總歸是會發(fā)生的。A哥經(jīng)?!敖趟簟背绦騿T要面向工資編程,雖然這價值觀有點扭曲,但不可否認很多小伙伴真是這么想的(命中你了沒有😄),稍加粉飾了而已。話粗理不粗哦,almost所有的Javaer都在用Spring,你憑什么工資比你身邊同事的高呢?

springboot static關(guān)鍵字真能提高Bean的優(yōu)先級(厲害了)

Spring對Bean的(生命周期)管理是它最為核心的能力,同時也是很復雜、很難掌握的一個知識點?,F(xiàn)在就可以啟動你的工程,有木有這句日志:

'Bean ’xxx’ of type [xxxx] is not eligible for getting processed by all BeanPostProcessors' + '(for example: not eligible for auto-proxying)'

這是一個典型的Spring Bean過早初始化問題,搜搜看你日志里是否有此句嘍。這句日志是由Spring的BeanPostProcessorChecker這個類負責輸出,含義為:你的Bean xxx不能被所有的BeanPostProcessors處理到(有的生命周期觸達不到),提醒你注意。此句日志在低些的版本里是warn警告級別,在本文約定的版本里官方把它改為了info級別。

絕大多數(shù)情況下,此句日志的輸出不會對你的功能造成影響,因此無需搭理。這也是Spring官方為何把它從warn調(diào)低為info級別的原因

我在CSDN上寫過一篇“Spring Bean過早初始化導致的誤傷”的文章,訪問量達近4w:

springboot static關(guān)鍵字真能提高Bean的優(yōu)先級(厲害了)

從這個數(shù)據(jù)(訪問量)上來看,這件事“并不簡單”,遇到此麻煩的小伙伴不在少數(shù)且確實難倒了一眾人。關(guān)于Spring Bean的順序,全局是不可控的,但是局部上它提供了多種方式來方便使用者提高/降低優(yōu)先級(比如前面的使用@AutoConfigureBefore調(diào)整配置順序竟沒生效?這篇文章),本文就聊聊static關(guān)鍵字對于提供Bean的優(yōu)先級的功效。

springboot static關(guān)鍵字真能提高Bean的優(yōu)先級(厲害了)

版本約定

本文內(nèi)容若沒做特殊說明,均基于以下版本:

JDK:1.8Spring Framework:5.2.2.RELEASE

正文

本文采用從 問題提出-結(jié)果分析-解決方案-原理剖析 這4個步驟,層層遞進的去感受static關(guān)鍵字在Spring Bean上的魅力~

警告一:來自BeanPostProcessorChecker

這是最為常見的一種警告,特別當你的工程使用了shiro做鑒權(quán)框架的時候。在我記憶中這一年來有N多位小伙伴問過我此問題,可見一斑。

@Configurationclass AppConfig { AppConfig() { System.out.println('AppConfig init...'); } @Bean BeanPostProcessor postProcessor() { return new MyBeanPostProcessor(); }}class MyBeanPostProcessor implements BeanPostProcessor { MyBeanPostProcessor() { System.out.println('MyBeanPostProcessor init...'); }}

運行程序,輸出結(jié)果:

AppConfig init...2020-05-31 07:40:50.979 INFO 15740 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean ’appConfig’ of type [com.yourbatman.config.AppConfig$$EnhancerBySpringCGLIB$$29b523c8] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)MyBeanPostProcessor init......

結(jié)果分析(問題點/沖突點):

AppConfig優(yōu)先于MyBeanPostProcessor進行實例化常識是:MyBeanPostProcessor作為一個后置處理器理應(yīng)是先被初始化的,而AppConfig僅僅是個普通Bean而已,初始化理應(yīng)靠后

出現(xiàn)了BeanPostProcessorChecker日志:表示AppConfig這個Bena不能被所有的BeanPostProcessors處理,所以有可能會讓它“錯過”容器對Bean的某些生命周期管理,因此可能損失某些能力(比如不能被自動代理),存在隱患但凡只要你工程里出現(xiàn)了BeanPostProcessorChecker輸出日志,理應(yīng)都得引起你的注意,因為這屬于Spring的警告日志(雖然新版本已下調(diào)為了info級別)

說明:這是一個Info日志,并非warn/error級別。絕大多數(shù)情況下你確實無需關(guān)注,但是如果你是一個容器開發(fā)者,建議請務(wù)必解決此問題(畢竟貌似大多數(shù)中間件開發(fā)者都有一定代碼潔癖😄)

解決方案:static關(guān)鍵字提升優(yōu)先級

基于上例,我們僅需做如下小改動:

AppConfig://@Bean//BeanPostProcessor postProcessor() {// return new MyBeanPostProcessor();//}// 方法前面加上static關(guān)鍵字@Beanstatic BeanPostProcessor postProcessor() { return new MyBeanPostProcessor();}

運行程序,結(jié)果輸出:

MyBeanPostProcessor init......AppConfig init......

那個煩人的BeanPostProcessorChecker日志就不見了,清爽了很多。同時亦可發(fā)現(xiàn)AppConfig是在MyBeanPostProcessor之后實例化的,這才符合我們所想的“正?!边壿嬄?。

警告二:Configuration配置類增強失敗

這個“警告”就比上一個嚴重得多了,它有極大的可能導致你程序錯誤,并且你還很難定位問題所在。

@Configurationclass AppConfig { AppConfig() { System.out.println('AppConfig init...'); } @Bean BeanDefinitionRegistryPostProcessor postProcessor() { return new MyBeanDefinitionRegistryPostProcessor(); }/////////////////////////////// @Bean Son son(){ return new Son(); } @Bean Parent parent(){ return new Parent(son()); }}class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor { MyBeanDefinitionRegistryPostProcessor() { System.out.println('MyBeanDefinitionRegistryPostProcessor init...'); } @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { }}

運行程序,結(jié)果輸出:

AppConfig init...MyBeanDefinitionRegistryPostProcessor init...2020-05-31 07:59:06.363 INFO 37512 --- [ main] o.s.c.a.ConfigurationClassPostProcessor : Cannot enhance @Configuration bean definition ’appConfig’ since its singleton instance has been created too early. The typical cause is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as ’static’....son init...hashCode() = 1300528434son init...hashCode() = 1598434875Parent init...

結(jié)果分析(問題點/沖突點):

AppConfig竟然比MyBeanDefinitionRegistryPostProcessor的初始化時機還早,這本就不合理 從ConfigurationClassPostProcessor 的日志中可看到:AppConfig配置類enhance增強失敗 Son對象竟然被創(chuàng)建了兩個不同的實例,這將會直接導致功能性錯誤

這三步結(jié)果環(huán)環(huán)相扣,因為1導致了2的增強失敗,因為2的增強失敗導致了3的創(chuàng)建多個實例,真可謂一步錯,步步錯。需要注意的是:這里ConfigurationClassPostProcessor輸出的依舊是info日志(我個人認為,Spring把這個輸出調(diào)整為warn級別是更為合理的,因為它影響較大)。

說明:對這個結(jié)果的理解基于對Spring配置類的理解,因此強烈建議你進我公眾號參閱那個可能是寫的最全、最好的Spring配置類專欄學習(文章不多,6篇足矣)

源碼處解釋:

ConfigurationClassPostProcessor:// 對Full模式的配置類嘗試使用CGLIB字節(jié)碼提升public void enhanceConfigurationClasses(ConfigurableListableBeanFactory beanFactory) {...// 對Full模式的配置類有個判斷/校驗if (ConfigurationClassUtils.CONFIGURATION_CLASS_FULL.equals(configClassAttr)) {if (!(beanDef instanceof AbstractBeanDefinition)) {throw new BeanDefinitionStoreException('Cannot enhance @Configuration bean definition ’' +beanName + '’ since it is not stored in an AbstractBeanDefinition subclass');}// 若判斷發(fā)現(xiàn)此時該配置類已經(jīng)是個單例Bean了(說明已初始化完成)// 那就不再做處理,并且輸出警告日志告知使用者(雖然是info日志)else if (logger.isInfoEnabled() && beanFactory.containsSingleton(beanName)) {logger.info('Cannot enhance @Configuration bean definition ’' + beanName +'’ since its singleton instance has been created too early. The typical cause ' +'is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor ' +'return type: Consider declaring such methods as ’static’.');}configBeanDefs.put(beanName, (AbstractBeanDefinition) beanDef);}...}

由于配置類增強是在BeanFactoryPostProcessor#postProcessBeanFactory()聲明周期階段去做的,而BeanDefinitionRegistryPostProcessor它會優(yōu)先于該步驟完成實例化(其實主要是優(yōu)先級比BeanFactoryPostProcessor高),從而間接帶動 AppConfig提前初始化導致了問題,這便是根本原因所在。

提問點:本處使用了個自定義的BeanDefinitionRegistryPostProcessor模擬了效果,那如果你是使用的BeanFactoryPostProcessor能出來這個效果嗎???答案是不能的,具體原因留給讀者思考,可參考:PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors這段流程輔助理解。

解決方案:static關(guān)鍵字提升優(yōu)先級

來吧,繼續(xù)使用static關(guān)鍵字改造一下:

AppConfig://@Bean//BeanDefinitionRegistryPostProcessor postProcessor() {// return new MyBeanDefinitionRegistryPostProcessor();//}@Beanstatic BeanDefinitionRegistryPostProcessor postProcessor() { return new MyBeanDefinitionRegistryPostProcessor();}

運行程序,結(jié)果輸出:

MyBeanDefinitionRegistryPostProcessor init......AppConfig init...son init...hashCode() = 2090289474Parent init......

完美。

警告三:非靜態(tài)@Bean方法導致@Autowired等注解失效

@Configurationclass AppConfig { @Autowired private Parent parent; @PostConstruct void init() { System.out.println('AppConfig.parent = ' + parent); } AppConfig() { System.out.println('AppConfig init...'); } @Bean BeanFactoryPostProcessor postProcessor() { return new MyBeanFactoryPostProcessor(); } @Bean Son son() { return new Son(); } @Bean Parent parent() { return new Parent(son()); }}class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor { MyBeanFactoryPostProcessor() { System.out.println('MyBeanFactoryPostProcessor init...'); } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { }}

運行程序,結(jié)果輸出:

AppConfig init...2020-05-31 08:28:06.550 INFO 1464 --- [ main] o.s.c.a.ConfigurationClassEnhancer : @Bean method AppConfig.postProcessor is non-static and returns an object assignable to Spring’s BeanFactoryPostProcessor interface. This will result in a failure to process annotations such as @Autowired, @Resource and @PostConstruct within the method’s declaring @Configuration class. Add the ’static’ modifier to this method to avoid these container lifecycle issues; see @Bean javadoc for complete details.MyBeanFactoryPostProcessor init......son init...hashCode() = 882706486Parent init...

結(jié)果分析(問題點/沖突點):

AppConfig提前于MyBeanFactoryPostProcessor初始化 @Autowired/@PostConstruct等注解沒有生效,這個問題很大

需要強調(diào)的是:此時的AppConfig是被enhance增強成功了的,這樣才有可能進入到BeanMethodInterceptor攔截里面,才有可能輸出這句日志(該攔截器會攔截Full模式配置列的所有的@Bean方法的執(zhí)行)

這句日志由ConfigurationClassEnhancer.BeanMethodInterceptor輸出,含義為:你的@Bean標注的方法是非static的并且返回了一個BeanFactoryPostProcessor類型的實例,這就導致了配置類里面的@Autowired, @Resource,@PostConstruct等注解都將得不到解析,這是比較危險的(所以其實這個日志調(diào)整為warn級別也是闊儀的)。

小細節(jié):為毛日志看起來是ConfigurationClassEnhancer這個類輸出的呢?這是因為BeanMethodInterceptor是它的靜態(tài)內(nèi)部類,和它共用的一個logger

源碼處解釋:

ConfigurationClassEnhancer.BeanMethodInterceptor:if (isCurrentlyInvokedFactoryMethod(beanMethod)) {if (logger.isInfoEnabled() && BeanFactoryPostProcessor.class.isAssignableFrom(beanMethod.getReturnType())) {logger.info(String.format('@Bean method %s.%s is non-static and returns an object ' +'assignable to Spring’s BeanFactoryPostProcessor interface. This will ' +'result in a failure to process annotations such as @Autowired, ' +'@Resource and @PostConstruct within the method’s declaring ' +'@Configuration class. Add the ’static’ modifier to this method to avoid ' +'these container lifecycle issues; see @Bean javadoc for complete details.',beanMethod.getDeclaringClass().getSimpleName(), beanMethod.getName()));}return cglibMethodProxy.invokeSuper(enhancedConfigInstance, beanMethodArgs);}

解釋為:如果當前正在執(zhí)行的@Bean方法(鐵定不是static,因為靜態(tài)方法它也攔截不到嘛)返回類型是BeanFactoryPostProcessor類型,那就輸出此警告日志來提醒使用者要當心。

解決方案:static關(guān)鍵字提升優(yōu)先級

AppConfig://@Bean//BeanFactoryPostProcessor postProcessor() {// return new MyBeanFactoryPostProcessor();//}@Beanstatic BeanFactoryPostProcessor postProcessor() { return new MyBeanFactoryPostProcessor();}

運行程序,結(jié)果輸出:

MyBeanFactoryPostProcessor init...AppConfig init...son init...hashCode() = 1906549136Parent init...// @PostConstruct注解生效嘍AppConfig.parent = com.yourbatman.bean.Parent@baf1bb3...

世界一下子又清爽了有木有。

原因總結(jié)

以上三個case是有共同點的,粗略的講導致它們的原因甚至是同一個:AppConfig這個Bean被過早初始化。然而我們的解決方案似乎也是同一個:使用static提升Bean的優(yōu)先級。

那么為何AppConfig會被提前初始化呢?為何使用static關(guān)鍵字就沒有問題了呢?根本原因可提前劇透:static靜態(tài)方法屬于類,執(zhí)行靜態(tài)方法時并不需要初始化所在類的實例;而實例方法屬于實例,執(zhí)行它時必須先初始化所在類的實例。聽起來是不是非常的簡單,JavaSE的東西嘛,當然只知曉到這個層次肯定是遠遠不夠的,限于篇幅原因,關(guān)于Spring是如何處理的源碼級別的分析我放在了下篇文章,請別走開喲~

static靜態(tài)方法一定優(yōu)先執(zhí)行嗎?

看完本文,有些小伙伴就忍不住躍躍欲試了,甚至很武斷的得出結(jié)論:static標注的@Bean方法優(yōu)先級更高,其實這是錯誤的,比如你看如下示例:

@Configurationclass AppConfig2 { AppConfig2(){ System.out.println('AppConfig2 init...'); } @Bean Son son() { return new Son(); } @Bean Daughter daughter() { return new Daughter(); } @Bean Parent Parent() { return new Parent(); }}

運行程序,結(jié)果輸出:

AppConfig2 init...son init...Daughter init...Parent init...

這時候你想讓Parent在Son之前初始化,因此你想著在用static關(guān)鍵字來提升優(yōu)先級,這么做:

AppConfig2://@Bean//Parent Parent() {// return new Parent();//}@Beanstatic Parent Parent() { return new Parent();}

結(jié)果:你徒勞了,static貌似并沒有生效,怎么回事?

原因淺析

為了滿足你的好奇心,這里給個淺析,道出關(guān)鍵因素。我們知道@Bean方法(不管是靜態(tài)方法還是實例方法)最終都會被封裝進ConfigurationClass實例里面,使用Set<BeanMethod> beanMethods存儲著,關(guān)鍵點在于它是個LinkedHashSet所以是有序的(存放順序),而存入的順序底層是由clazz.getDeclaredMethods()來決定的,由此可知@Bean方法執(zhí)行順序和有無static沒有半毛錢關(guān)系。

springboot static關(guān)鍵字真能提高Bean的優(yōu)先級(厲害了)

說明:clazz.getDeclaredMethods()得到的是Method[]數(shù)組,是有序的。這個順序由字節(jié)碼(定義順序)來保證:先定義,先服務(wù)。

由此可見,static并不是真正意義上的提高Bean優(yōu)先級,對于如上你的需求case,你可以使用@DependsOn注解來保證,它也是和Bean順序息息相關(guān)的一個注解,在本專欄后續(xù)文章中將會詳細講到。

所以關(guān)于@Bean方法的執(zhí)行順序的正確結(jié)論應(yīng)該是:在同一配置類內(nèi),在無其它“干擾”情況下(無@DependsOn、@Lazy等注解),@Bean方法的執(zhí)行順序遵從的是定義順序(后置處理器類型除外)。

小提問:如果是垮@Configuration配置類的情況,順序如何界定呢?那么這就不是同一層級的問題了,首先考慮的應(yīng)該是@Configuration配置類的順序問題,前面有文章提到過配置類是支持有限的的@Order注解排序的,具體分析請依舊保持關(guān)注A哥后續(xù)文章詳解哈...

static關(guān)鍵字使用注意事項

在同一個@Configuration配置類內(nèi),對static關(guān)鍵字的使用做出如下說明,供以參考:

對于普通類型(非后置處理器類型)的@Bean方法,使用static關(guān)鍵字并不能改變順序(按照方法定義順序執(zhí)行),所以別指望它static關(guān)鍵字一般有且僅用于@Bean方法返回為BeanPostProcessor、BeanFactoryPostProcessor等類型的方法,并且建議此種方法請務(wù)必使用static修飾,否則容易導致隱患,埋雷

static關(guān)鍵字不要濫用(其實任何關(guān)鍵字皆勿亂用),在同一配置類內(nèi),與其說它是提升了Bean的優(yōu)先級,倒不如說它讓@Bean方法靜態(tài)化從而不再需要依賴所在類的實例即可獨立運行。另外我們知道,static關(guān)鍵還可以修飾(內(nèi)部)類,那么如果放在類上它又是什么表現(xiàn)呢?同樣的,你先思考,下篇文章我們接著聊~

說明:使用static修飾Class類在Spring Boot自動配置類里特別特別常見,所以掌握起來很具價值

思考題:

今天的思考題比較簡單:為何文首三種case的警告信息都是info級別呢?是否有級別過低之嫌?

總結(jié)

本文還是蠻干的哈,不出意外它能夠幫你解決你工程中的某些問題,排除掉一些隱患,畢竟墨菲定律被驗證了你擔心的事它總會發(fā)生,防患于未然才能把自己置于安全高地嘛。

你可能詫異,A哥竟能把static關(guān)鍵字在Spring中的應(yīng)用都能寫出個專欄出來,是的,這不是就是本公眾號的定位么 ,小而美和拒絕淺嘗輒止嘛。對于一些知識(比如本文的static關(guān)鍵字的使用)我并不推崇強行記憶,因為那真的很容易忘,快速使用可以簡單記記,但真想記得牢(甚至成為永久記憶),那必須得去深水區(qū)看看。來吧,下文將授之以漁~

很多小伙伴去強行記憶Spring Boot支持的那17種外部化配置,此時你應(yīng)該問自己:現(xiàn)在你可能記得,一周以后呢?一個月以后呢?所以你需要另辟蹊徑,那就持續(xù)關(guān)注我吧😄

到此這篇關(guān)于springboot static關(guān)鍵字真能提高Bean的優(yōu)先級(厲害了)的文章就介紹到這了,更多相關(guān)spring boot static關(guān)鍵字內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!

標簽: Spring
相關(guān)文章:
主站蜘蛛池模板: 日本三级欧美三级人妇英文 | 久久伊人男人的天堂网站 | 二区久久国产乱子伦免费精品 | 完整日本特级毛片 | 久久国产精品最新一区 | 久色网址| 久久亚洲欧美成人精品 | 综合在线视频 | 久久久久久久99精品免费 | 欧美日韩视频在线第一区二区三区 | 国产在线手机视频 | 毛片网站免费在线观看 | 嫩草影院在线观看网站成人 | 欧美一级一极性活片免费观看 | 国产成人久久精品二区三区牛 | 综合558欧美成人永久网站 | 久久久久久免费精品视频 | 杨幂国产精品福利在线观看 | 午夜免费片在线观看不卡 | 国产一区二区免费播放 | 亚洲第一成人在线 | 欧美一级片免费观看 | 欧美大片毛片大片 | 9191久久久久视频 | 日韩黄色一级片 | 亚洲社区在线 | 91精品成人免费国产 | 国产一级第一级毛片 | 天堂1在线观看 | 免费看黄色三级毛片 | 好吊操这里只有精品 | 欧美日韩一区二区综合在线视频 | 精品99在线观看 | 久久久免费视频观看 | 欧美曰韩一区二区三区 | 欧美在线播放视频 | 在线久草视频 | 国产深夜福利视频在线播放 | 欧美孕妇性xxxⅹ精品hd | 日本经典在线三级视频 | 亚洲伦乱 |