ApplicationContextInitializer是在springboot启动过程(refresh方法前)调用,主要是在ApplicationContextInitializer中initialize方法中拉起了ConfigurationClassPostProcessor这个类(我在springboot启动流程中有描述),通过这个processor实现了beandefinition。
ApplicationContextInitializer实现的3种方式:
首先创建一个实现ApplicationContextInitializer的类:
public class MyApplicationContextInitializer implements ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
System.out.println("My ApplicationContextInitializer ...");
}
}
1. 使用spring.factories
- 在resources目录下创建META-INF文件夹
创建spring.factories
org.springframework.context.ApplicationContextInitializer=\
com.mxiaoy.springbootstarterdemo.initializer.MyApplicationContextInitializer
2. application.properties添加配置
直接application.properties
context.initializer.classes = com.mxiaoy.springbootstarterdemo.initializer.MyApplicationContextInitializer
3. 直接通过add方法
public static void main(String[] args) {
// SpringApplication.run(SpringBootStarterDemoApplication.class, args);
SpringApplication springApplication = new SpringApplication(SpringBootStarterDemoApplication.class);
// 添加实现了ApplicationContextInitializer的自定义类
springApplication.addInitializers(new MyApplicationContextInitializer());
springApplication.run(args);
}