springboot 系统初始化器自定义实现
程序员文章站
2022-05-23 18:13:48
...
springboot 系统初始化器二种自定义实现
第一种:
- 实现ApplicationContextInitalizer接口
@Order(1)
public class FirstInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
ConfigurableEnvironment environment=configurableApplicationContext.getEnvironment();
Map<String,Object> map=new HashMap<>();
map.put("key1","value1");
MapPropertySource mapPropertySource = new MapPropertySource("firstInitializer", map);
environment.getPropertySources().addLast(mapPropertySource);
System.out.println("run firstInitializer");
}
}
- 在resources下新建META-INF文件夹,新建spring.factories中定义
org.springframework.context.ApplicationContextInitializer=com.example.gogoboot.initializer.FirstInitializer
第二种:
- 实现ApplicationContextInitalizer接口
@Order(1)
public class SecondInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
ConfigurableEnvironment environment=configurableApplicationContext.getEnvironment();
Map<String,Object> map=new HashMap<>();
map.put("key2","value2");
MapPropertySource mapPropertySource = new MapPropertySource("SecondInitializer", map);
environment.getPropertySources().addLast(mapPropertySource);
System.out.println("run SecondInitializer");
}
}
- 通过SpringApplication类初始化后设置进去
@SpringBootApplication
public class GogoBootApplication {
public static void main(String[] args) {
// SpringApplication.run(GogoBootApplication.class, args);
SpringApplication springApplication = new SpringApplication(GogoBootApplication.class);
springApplication.addInitializers(new SecondInitializer());
springApplication.run(args);
}
}
第三种:
- 实现ApplicationContextInitalizer接口
@Order(1)
public class ThirdInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
ConfigurableEnvironment environment=configurableApplicationContext.getEnvironment();
Map<String,Object> map=new HashMap<>();
map.put("key3","value3");
MapPropertySource mapPropertySource = new MapPropertySource("ThirdInitializer", map);
environment.getPropertySources().addLast(mapPropertySource);
System.out.println("run ThirdInitializer");
}
}
- 在application.yml种配置如下内容
context:
initializer:
classes: com.example.gogoboot.initializer.ThirdInitializer