ApplicationContextInitializer是在springboot启动过程(refresh方法前)调用,主要是在ApplicationContextInitializer中initialize方法中拉起了ConfigurationClassPostProcessor这个类(我在springboot启动流程中有描述),通过这个processor实现了beandefinition。

ApplicationContextInitializer实现的3种方式:

首先创建一个实现ApplicationContextInitializer的类:

  1. public class MyApplicationContextInitializer implements ApplicationContextInitializer {
  2. @Override
  3. public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
  4. System.out.println("My ApplicationContextInitializer ...");
  5. }
  6. }

1. 使用spring.factories

  1. 在resources目录下创建META-INF文件夹
  2. 创建spring.factories

    1. org.springframework.context.ApplicationContextInitializer=\
    2. com.mxiaoy.springbootstarterdemo.initializer.MyApplicationContextInitializer

    2. application.properties添加配置

  3. 直接application.properties

    1. context.initializer.classes = com.mxiaoy.springbootstarterdemo.initializer.MyApplicationContextInitializer

    3. 直接通过add方法

    1. public static void main(String[] args) {
    2. // SpringApplication.run(SpringBootStarterDemoApplication.class, args);
    3. SpringApplication springApplication = new SpringApplication(SpringBootStarterDemoApplication.class);
    4. // 添加实现了ApplicationContextInitializer的自定义类
    5. springApplication.addInitializers(new MyApplicationContextInitializer());
    6. springApplication.run(args);
    7. }