spring security oauth2 @EnableAuthorizationServer初始化時所有的bean都爲null

在自己開發spring security oauth2 jwt時,發現jwt不生效,debug才知道,EnableAuthorizationServer啓動的時候所有的bean都爲Null ,當然加載不了jwt,一開始以爲是bean加載順序問題,然後無論怎麼調順序都沒反應,最後各種查資料,解決方式如下:

    引用 bean創建文檔的一句:

A note on BeanFactoryPostProcessor-returning @Bean methods <p> Special consideration must be taken for @Bean methods that return Spring BeanFactoryPostProcessor (BFPP) types. Because BFPP objects must be instantiated very early in the container lifecycle, they can interfere with processing of annotations such as @Autowired, @Value, and @PostConstruct within @Configuration classes. To avoid these lifecycle issues, mark BFPP-returning @Bean methods as static. For example:</p> <p>      @Bean
     public static PropertyPlaceholderConfigurer ppc() {
         // instantiate, configure and return ppc …
     }
By marking this method as static, it can be invoked without causing instantiation of its declaring @Configuration class, thus avoiding the above-mentioned lifecycle conflicts. Note however that static @Bean methods will not be enhanced for scoping and AOP semantics as mentioned above. This works out in BFPP cases, as they are not typically referenced by other @Bean methods. As a reminder, a WARN-level log message will be issued for any non-static @Bean methods having a return type assignable to BeanFactoryPostProcessor.</p>

這段意思大概是說,類似PropertyPlaceholderConfigurer這種的Bean是需要在其他Bean初始化之前完成的,這會影響到Spring Bean生命週期的控制,所以如果你用到了這樣的Bean,需要把他們聲明成Static的,這樣就會不需要@Configuration的實例而調用,從而提前完成Bean的構造。並且,這裏還提到,如果你沒有把實現 BeanFactoryPostProcessor接口的Bean聲明爲static的,他會給出警告。

簡單來說就是,你的程序中有地方配置bean的時候不規範,或者有重複的,就會影響到其他Bean的生命週期。

後面修改好後就可以了。BUG解決!


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