springboot的事件在org.springframework.boot.context.event包下,可通过GenericApplicationListener监听。
springboot的LoggingApplicationListener集成此接口实现。
可以参考此设计来实现我们自己的一些系统配置的自定义业务。
事件如下:
GenericApplicationListener
public interface GenericApplicationListener extends ApplicationListener<ApplicationEvent>, Ordered{
}
GenericApplicationListener可用来监听springboot的以下事件(按照先后顺序):
- ApplicationContextInitializedEvent
事件发布时机:springApplicaiton开始启动,ApplicationContextInitializers被调用,但是bean还没有被加载。
- ApplicationPreparedEvent
- ContextRefreshedEvent
- ApplicationStartedEvent
事件发布时机:applicationContext已更新但是还没有调用ApplicationRunner/ConmandLineRunnder
- AvailabilityChangeEvent
- ApplicationReadyEvent
事件发布时机:服务启动成功。
- ContextClosedEvent
使用:
- 创建Listener继承GenericApplicationListener
public class TestRunListener implements GenericApplicationListener {
public static final int DEFAULT_ORDER = Ordered.HIGHEST_PRECEDENCE + 100;
private static final Logger logger = LoggerFactory.getLogger(TestRunListener.class);
SpringApplication application = null;
String[] args = null;
@Override
public boolean supportsEventType(ResolvableType eventType) {
logger.info("eventType:{}",eventType.toString());
return true;
}
@Override
public int getOrder() {
return DEFAULT_ORDER;
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
logger.info("TestRun,eventType is:{}",event.toString());
}
}
2, 注册到application
@SpringBootApplication
public class LogTestApplication {
private static final Logger logger = LoggerFactory.getLogger(LogTestApplication.class);
public static void main(String[] args) {
SpringApplication application = new SpringApplication(LogTestApplication.class);
application.addListeners(new TestRunListener());
application.run(args);
}
}