springboot 系统事件监听

springboot的事件在org.springframework.boot.context.event包下,可通过GenericApplicationListener监听。
springboot的LoggingApplicationListener集成此接口实现。
在这里插入图片描述

可以参考此设计来实现我们自己的一些系统配置的自定义业务。
事件如下:

GenericApplicationListener

public interface GenericApplicationListener extends ApplicationListener<ApplicationEvent>, Ordered{
    
}

GenericApplicationListener可用来监听springboot的以下事件(按照先后顺序):

  1. ApplicationContextInitializedEvent

事件发布时机:springApplicaiton开始启动,ApplicationContextInitializers被调用,但是bean还没有被加载。

  1. ApplicationPreparedEvent
  2. ContextRefreshedEvent
  3. ApplicationStartedEvent

事件发布时机:applicationContext已更新但是还没有调用ApplicationRunner/ConmandLineRunnder

  1. AvailabilityChangeEvent
  2. ApplicationReadyEvent

事件发布时机:服务启动成功。

  1. ContextClosedEvent
使用:
  1. 创建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);
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值