1.前言
最近遇到了这种情况,有一个类A需要交给spring管理,但是在创建A实例时,需要读取配置文件中的值来初始化一部分属性,例如下面情况。当然我们可以使用spring的注解,本着学习的态度,我试着模拟一下。
/** 这个参数需要配置文件中读取 */
public A(int threadNum){
this.b=new B(threadNum);
}
2.思路
由于我们项目使用spring boot来构建,而spring boot在启动过程中发布了各种事件,因此我们只需利用这些事件便可完成不同阶段需要的操作。在这里使用了spring boot的两种事件,分别完成配置文件初始化,BeanFactoryPostProcessor的注入。
1.ApplicationStartingEvent
An ApplicationStartingEvent is sent at the start of a run but before any processing, except for the registration of listeners and initializers
从官方的说明中我们可以得知ApplicationStartingEvent 事件是在启动时就会发布,因此我们可以在这里进行配置文件读取的操作。
2.ApplicationPreparedEvent
An ApplicationPreparedEvent is sent just before the refresh is started but after bean definitions have been loaded.
从官方的说明中我们可以得知,当spring已经加载BeanDefinition后,但是还未执行refresh()前发布此事件,没有执行refresh()表明我们可以在这个事件发生时手动往spring容器中注册一个BeanFactory处理器,而不是将我们的BeanFactory交给spring去扫描。
3.实现
1.定义注解
这部分比较简单就是自定义一个注解,用于标记这个构造方法需要处理。
public @interface QProperty {
String name();
int order() default 0;
}
2.监听事件
先看