Spring Boot引入了一个新的扩展接口
SpringApplicationRunListener
,可以监听Spring Application启动过程的各个阶段,比如应用开始启动、环境ready、上下文ready等
TenmaoRunListener
需要注意的就是构造函数,比如接受两个参数SpringApplication application, String[] args
。这一点也蛮有意思,为什么扩展机制还需要有一些潜规则呢?是不是接口上实现这两个参数的赋值是不是更好一些?@Slf4j
public class TenmaoRunListener implements SpringApplicationRunListener {
public TenmaoRunListener(SpringApplication application, String[] args) {
log.info("TenmaoRunListener Constructor: application[{}] args: {}",
application.getMainApplicationClass(), Arrays.toString(args));
}
@Override
public void starting(ConfigurableBootstrapContext bootstrapContext) {
log.info("starting");
}
@Override
public void environmentPrepared(ConfigurableBootstrapContext bootstrapContext, ConfigurableEnvironment environment) {
log.info("environmentPrepared");
}
@Override
public void contextPrepared(ConfigurableApplicationContext context) {
log.info("contextPrepared");
}
@Override
public void contextLoaded(ConfigurableApplicationContext context) {
log.info("contextLoaded");
}
@Override
public void started(ConfigurableApplicationContext context) {
log.info("started");
}
@Override
public void running(ConfigurableApplicationContext context) {
log.info("running");
}
@Override
public void failed(ConfigurableApplicationContext context, Throwable exception) {
log.info("failed");
}
}
resources/META-INF/spring.factories
org.springframework.boot.SpringApplicationRunListener=com.tenmao.initializer.TenmaoRunListener
EventPublishingRunListener
使用了这个扩展接口