spring-boot ApplicationContextIn
2017-09-24 本文已影响409人
八目朱勇铭
ApplicationContextInitializer是在ConfigurableApplicationContext刷新之前初始化Spring ConfigurableApplicationContext的回调接口。当执行:
ConfigurableApplicationContext.refresh()或SpringApplication.run()
时生效。
实现方式
1)编写MyApplicationContextInitializer
,实现ApplicationContextInitializer
接口。
public class MyApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
System.out.println("=======“);
}
}
启动BlogApplication
@SpringBootApplication
public class BlogApplication {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(BlogApplication.class);
//关键一步:将一个或多个initializer加入至spring容器中
springApplication.addInitializers(new MyApplicationContextInitializer());
springApplication.run(args).close();
}
}
console result
2)在application.properties中以context.initializer.classes
为key配置一个或多个自定义Initializer
在
BlogApplication
中注释掉springApplication.addInitializers();
@SpringBootApplication
public class BlogApplication {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(BlogApplication.class);
//springApplication.addInitializers(new MyApplicationContextInitializer());
springApplication.run(args).close();
}
}
console result
3)在META-INF/spring.factories中以org.springframework.context.ApplicationContextInitializer
为key配置一个或多个initialier
执行结果和上图一样。
至此,springboot中的ApplicationContextInitializer实现与使用就结束啦,喜欢的读者可以持续关注我的springboot系列博客~