前言
Spring Bean整体上是无序的,而现实是大多数情况下我们真的无需关心,无序就无序呗,无所谓喽。但是(此处应该有但是哈),我有理由相信,对于有一定从业经验的 Javaer 来说,或多或少都经历过 Bean 初始化顺序带来的“困扰”,也许是因为没有对你的功能造成影响,也许可能是你全然“不知情”,所以最终就不了了之~
Spring 对 Bean 的(生命周期)管理是它最为核心的能力,同时也是很复杂、很难掌握的一个知识点。现在就可以启动你的工程,有木有这句日志:
"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 级别。
绝大多数情况下,此句日志的输出不会对你的功能造成影响,因此无需搭理。这也是 Spring 官方为何把它从 warn 调低为 info 级别的原因就聊聊static 关键字对于提供 Bean 的优先级的功效。
版本约定
本文内容若没做特殊说明,均基于以下版本:
- JDK:
1.8 - Spring Framework:
5.2.2.RELEASE
本文采用从 问题提出-结果分析-解决方案-原理剖析 这 4 个步骤,层层递进的去感受 static 关键字在 Spring Bean 上的魅力~
警告一:来自 BeanPostProcessorChecker
这是最为常见的一种警告,特别当你的工程使用了shiro做鉴权框架的时候。在我记忆中这一年来有 N 多位小伙伴问过我此问题,可见一斑。
@Configuration
class AppConfig {
AppConfig() {
System.out.println("AppConfig init...");
}
@Bean
BeanPostProcessor postProcessor() {
return new MyBeanPostProcessor();
}
}
class MyBeanPostProcessor implements BeanPostProcessor {
MyBeanPostProcessor() {
System.out.println("MyBeanPostProcessor init...");
}
}
运行程序,输出结果:
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...
...
结果分析(问题点/冲突点):
AppConfig优先于MyBeanPostProcessor进行实例化- 常识是:
MyBeanPostProcessor作为一个后置处理器理应是先被初始化的,而AppConfig仅仅是个普通 Bean 而已,初始化理应靠后
- 常识是:
- 出现了
BeanPostProcessorChecker日志:表示AppConfig这个 Bena 不能被所有的 BeanPostProcessors 处理,所以有可能会让它“错过”容器对 Bean 的某些生命周期管理,因此可能损失某些能力(比如不能被自动代理),存在隐患- 但凡只要你工程里出现了
BeanPostProcessorChecker输出日志,理应都得引起你的注意,因为这属于 Spring 的警告日志(虽然新版本已下调为了 info 级别)
- 但凡只要你工程里出现了
说明:这是一个 Info 日志,并非 warn/error 级别。绝大多数情况下你确实无需关注,但是如果你是一个容器开发者,建议请务必解决此问题(毕竟貌似大多数中间件开发者都有一定代码洁癖😄)
解决方案:static 关键字提升优先级
基于上例,我们仅需做如下小改动:
AppConfig:
//@Bean
//BeanPostProcessor postProcessor() {
// return new MyBeanPostProcessor();
//}
// 方法前面加上 static 关键字
@Bean
static BeanPostProcessor postProcessor() {
return new MyBeanPostProcessor();
}
运行程序,结果输出:
MyBeanPostProcessor init...
...
AppConfig init...
...
那个烦人的BeanPostProcessorChecker日志就不见了,清爽了很多。同时亦可发现AppConfig是在MyBeanPostProcessor之后实例化的,这才符合我们所想的“正常”逻辑嘛。
警告二:Configuration 配置类增强失败
这个“警告”就比上一个严重得多了,它有极大的可能导致你程序错误,并且你还很难定位问题所在。
@Configuration
class 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 {
}
}
运行程序,结果输出:
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() = 1300528434
son init...hashCode() = 1598434875
Parent init...
结果分析(问题点/冲突点):
- AppConfig 竟然比 MyBeanDefinitionRegistryPostProcessor 的初始化时机还早,这本就不合理
- 从
ConfigurationClassPostProcessor的日志中可看到:AppConfig 配置类 enhance 增强失败 - Son 对象竟然被创建了两个不同的实例,这将会直接导致功能性错误
这三步结果环环相扣,因为 1 导致了 2 的增强失败,因为 2 的增强失败导致了 3 的创建多个实例,真可谓一步错,步步错。需要注意的是:这里 ConfigurationClassPostProcessor 输出的依旧是 info 日志(我个人认为,Spring 把这个输出调整为 warn 级别是更为合理的,因为它影响较大)。
说明:对这个结果的理解基于对 Spring 配置类的理解,因此强烈建议你进我公众号参阅那个可能是写的最全、最好的 Spring 配置类专栏学习(文章不多,6 篇足矣)
源码处解释:
ConfigurationClassPostProcessor:
// 对 Full 模式的配置类尝试使用 CGLIB 字节码提升
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");
}
// 若判断发现此时该配置类已经是个单例 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它会优先于该步骤完成实例化(其实主要是优先级比BeanFactoryPostProcessor高),从而间接带动 AppConfig 提前初始化导致了问题,这便是根本原因所在。
提问点:本处使用了个自定义的BeanDefinitionRegistryPostProcessor模拟了效果,那如果你是使用的BeanFactoryPostProcessor能出来这个效果吗???答案是不能的,具体原因留给读者思考,可参考:PostProcessorRegistrationDelegate##invokeBeanFactoryPostProcessors这段流程辅助理解。
解决方案:static 关键字提升优先级
来吧,继续使用 static 关键字改造一下:
AppConfig:
//@Bean
//BeanDefinitionRegistryPostProcessor postProcessor() {
// return new MyBeanDefinitionRegistryPostProcessor();
//}
@Bean
static BeanDefinitionRegistryPostProcessor postProcessor() {
return new MyBeanDefinitionRegistryPostProcessor();
}
运行程序,结果输出:
MyBeanDefinitionRegistryPostProcessor init...
...
AppConfig init...
son init...hashCode() = 2090289474
Parent init...
...
完美。
警告三:非静态@Bean 方法导致@Autowired 等注解失效
@Configuration
class 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 {
}
}
运行程序,结果输出:
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() = 882706486
Parent init...
结果分析(问题点/冲突点):
- AppConfig 提前于
MyBeanFactoryPostProcessor初始化 @Autowired/@PostConstruct等注解没有生效,这个问题很大
需要强调的是:此时的 AppConfig 是被 enhance 增强成功了的,这样才有可能进入到
BeanMethodInterceptor拦截里面,才有可能输出这句日志(该拦截器会拦截 Full 模式配置列的所有的@Bean 方法的执行)
这句日志由ConfigurationClassEnhancer.BeanMethodInterceptor输出,含义为:你的@Bean 标注的方法是非 static 的并且返回了一个BeanFactoryPostProcessor类型的实例,这就导致了配置类里面的@Autowired, @Resource,@PostConstruct等注解都将得不到解析,这是比较危险的(所以其实这个日志调整为 warn 级别也是阔仪的)。
小细节:为毛日志看起来是 ConfigurationClassEnhancer 这个类输出的呢?这是因为
BeanMethodInterceptor是它的静态内部类,和它共用的一个 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);
}
解释为:如果当前正在执行的@Bean 方法(铁定不是 static,因为静态方法它也拦截不到嘛)返回类型是BeanFactoryPostProcessor类型,那就输出此警告日志来提醒使用者要当心。
解决方案:static 关键字提升优先级
AppConfig:
//@Bean
//BeanFactoryPostProcessor postProcessor() {
// return new MyBeanFactoryPostProcessor();
//}
@Bean
static BeanFactoryPostProcessor postProcessor() {
return new MyBeanFactoryPostProcessor();
}
运行程序,结果输出:
MyBeanFactoryPostProcessor init...
AppConfig init...
son init...hashCode() = 1906549136
Parent init...
// @PostConstruct 注解生效喽
AppConfig.parent = com.yourbatman.bean.Parent@baf1bb3
...
世界一下子又清爽了有木有。
原因总结
以上三个 case 是有共同点的,粗略的讲导致它们的原因甚至是同一个:AppConfig 这个 Bean 被过早初始化。然而我们的解决方案似乎也是同一个:使用 static 提升 Bean 的优先级。
那么为何 AppConfig 会被提前初始化呢?为何使用 static 关键字就没有问题了呢?根本原因可提前剧透:static 静态方法属于类,执行静态方法时并不需要初始化所在类的实例;而实例方法属于实例,执行它时必须先初始化所在类的实例。听起来是不是非常的简单,JavaSE 的东西嘛,当然只知晓到这个层次肯定是远远不够的,限于篇幅原因,关于 Spring 是如何处理的源码级别的分析我放在了下篇文章,请别走开哟~
static 静态方法一定优先执行吗?
看完本文,有些小伙伴就忍不住跃跃欲试了,甚至很武断的得出结论:static 标注的@Bean 方法优先级更高,其实这是错误的,比如你看如下示例:
@Configuration
class 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();
}
}
运行程序,结果输出:
AppConfig2 init...
son init...
Daughter init...
Parent init...
这时候你想让 Parent 在 Son 之前初始化,因此你想着在用 static 关键字来提升优先级,这么做:
AppConfig2:
//@Bean
//Parent Parent() {
// return new Parent();
//}
@Bean
static Parent Parent() {
return new Parent();
}
结果:你徒劳了,static 貌似并没有生效,怎么回事?
原因浅析
为了满足你的好奇心,这里给个浅析,道出关键因素。我们知道@Bean 方法(不管是静态方法还是实例方法)最终都会被封装进ConfigurationClass实例里面,使用Set<BeanMethod> beanMethods存储着,关键点在于它是个LinkedHashSet所以是有序的(存放顺序),而存入的顺序底层是由clazz.getDeclaredMethods()来决定的,由此可知@Bean 方法执行顺序和有无 static 没有半毛钱关系。
说明:
clazz.getDeclaredMethods()得到的是 Method[]数组,是有序的。这个顺序由字节码(定义顺序)来保证:先定义,先服务。
由此可见,static 并不是真正意义上的提高 Bean 优先级,对于如上你的需求 case,你可以使用@DependsOn注解来保证,它也是和 Bean 顺序息息相关的一个注解,在本专栏后续文章中将会详细讲到。
所以关于@Bean 方法的执行顺序的正确结论应该是:在同一配置类内,在无其它“干扰”情况下(无@DependsOn、@Lazy 等注解),@Bean 方法的执行顺序遵从的是定义顺序(后置处理器类型除外)。
小提问:如果是垮@Configuration 配置类的情况,顺序如何界定呢?那么这就不是同一层级的问题了,首先考虑的应该是@Configuration 配置类的顺序问题,前面有文章提到过配置类是支持有限的的@Order 注解排序的,具体分析请依旧保持关注 A 哥后续文章详解哈...
static 关键字使用注意事项
在同一个@Configuration配置类内,对 static 关键字的使用做出如下说明,供以参考:
- 对于普通类型(非后置处理器类型)的@Bean 方法,使用 static 关键字并不能改变顺序(按照方法定义顺序执行),所以别指望它
- static 关键字一般有且仅用于@Bean 方法返回为
BeanPostProcessor、BeanFactoryPostProcessor等类型的方法,并且建议此种方法请务必使用 static 修饰,否则容易导致隐患,埋雷
static 关键字不要滥用(其实任何关键字皆勿乱用),在同一配置类内,与其说它是提升了 Bean 的优先级,倒不如说它让@Bean 方法静态化从而不再需要依赖所在类的实例即可独立运行。另外我们知道,static 关键还可以修饰(内部)类,那么如果放在类上它又是什么表现呢?同样的,你先思考,下篇文章我们接着聊~
说明:使用 static 修饰 Class 类在Spring Boot自动配置类里特别特别常见,所以掌握起来很具价值
思考题
今天的思考题比较简单:为何文首三种 case 的警告信息都是 info 级别呢?是否有级别过低之嫌?
总结
本文还是蛮干的哈,不出意外它能够帮你解决你工程中的某些问题,排除掉一些隐患,毕竟墨菲定律被验证了你担心的事它总会发生,防患于未然才能把自己置于安全高地嘛。小编这边整理了一些Java核心技术知识点集锦200多页资料集锦,关注公众号:麒麟改bug ,编程的世界永远向所有热爱编程的人开放,这是一个自由,平等,共享的世界,我始终是这样坚信的。