在自己开发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解决!