spring boot 系统启动事件和失败事件监听
监听spring boot 服务的启动与失败,在服务启动后可能需要处理一些的业务
github代码链接 service-common 模块中
- 服务启动成功事件
@Component
public class ApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> {
private static Logger logger = LoggerFactory.getLogger(ApplicationReadyEventListener.class);
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
EventUtil.dispatcher(IStartupEvent.class);
}
}
2.服务启动失败事件
@Component
public class ApplicationFailedEventListener implements ApplicationListener<ApplicationFailedEvent> {
private static Logger logger = LoggerFactory.getLogger(ApplicationFailedEventListener.class);
@Override
public void onApplicationEvent(ApplicationFailedEvent event) {
logger.info("系统启动失败......");
}
}
3.事件分发机制
通过继承IEvent 实现事件的分发处理,更加简洁的处理一些业务的中操作,比如日志等,将代码的更好的解耦
(1)创建启动事件接口 继承IEvent
public interface IStartupEvent extends IEvent{
}
(2)实现IStartupEvent 接口,execute 执行对应方法
@Component
public class SyetemStartupEventImpl implements IStartupEvent {
private static Logger logger = LoggerFactory.getLogger(SyetemStartupEventImpl.class);
@Override
public int order() {
return 0;
}
@Override
public void execute(Object... objects) {
logger.info("服务启动成功。。。。。。");
}
}
(3)使用方式,会找到对应实现类
EventUtil.dispatcher(IStartupEvent.class);