springboot学习(八) 自定义监听

自定义监听

springboot 监听器有很多种,主要包括6种:
ApplicationEnvironmentPreparedListener
ApplicationFailedListener
ApplicationPreparedListener
ApplicationReadyListener
ApplicationStartingListener
SpringApplicationListener
各种监听器的意义可在网上查到很多资料。这里讲解的是自定义一个自己的监听事件,可以作一些特殊处理。这里假设在 ApplicationStartedEvent后触发另一个自定义监听。

自定义一个event 继承ApplicationEvent

public class MyApplicationEvent extends ApplicationEvent {
    private String msg;

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getMsg() {
        return msg;
    }

    /**
     * Create a new ApplicationEvent.
     *
     * @param source the object on which the event initially occurred (never {@code null})
     */

    public MyApplicationEvent(Object source) {
        super(source);
    }
}

自定义监听器实现ApplicationListener

@Slf4j
public class MyCustomListener implements ApplicationListener<MyApplicationEvent> {
    @Override
    public void onApplicationEvent(MyApplicationEvent event) {
        String msg = event.getMsg();
        log.info(msg);
    }
}

使用applicationContext触发这个自定义事件,这里只是举个例子,可以在任何其他地方触发这个事件 applicationContext #publishEvent(myEvent);

@Slf4j
public class MyStartedListener implements ApplicationListener<ApplicationStartedEvent> {
    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        log.info("服务已经启动啦");
        MyApplicationEvent myEvent = new MyApplicationEvent("myEvent");
        myEvent.setMsg("我自定义了一个事件");
        event.getApplicationContext().publishEvent(myEvent);

    }
}

因为这里是在MyStartedListener 这个监听里触发的,那么把这俩自定义的监听都添加一下

public static void main(String[] args) {
        SpringApplication springApplication = new SpringApplication(BootApplication.class);
        springApplication.addListeners(new MyStartedListener(), new MyCustomListener());
        springApplication.run( args);
    }

github 源码
上一篇 springboot 各种方式的校验
下一篇 websocket stomp配置,与session的结合以及ws/wss协议的使用

猜你喜欢

转载自blog.csdn.net/u011943534/article/details/80958949
今日推荐