前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot事件监听

SpringBoot事件监听

作者头像
HUC思梦
发布2020-09-03 16:50:50
3.4K0
发布2020-09-03 16:50:50
举报

代码演示:

代码语言:javascript
复制
package com.boot.event.eventdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class EventDemoApplication {

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(EventDemoApplication.class);
        //第一种方式 添加监听事件
        // app.addListeners(new MyApplicationListener());
        ConfigurableApplicationContext context = app.run(args);
        // 发布事件
        context.publishEvent(new MyApplicationEvent(new Object()));

        context.close();
    }
}
代码语言:javascript
复制
package com.boot.event.eventdemo;

import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class HandlerEvent {
//第四种方式,最常用方式    
    @EventListener(MyApplicationEvent.class)
    public void handlerEvent(MyApplicationEvent event) {
        System.out.println("接受到了事件====:"+event.getClass());
        System.out.println("接受到了事件====:"+event.getSource());
    }

    @EventListener(ContextClosedEvent.class)
    public void handlerEvent1(Object event) {
        System.out.println("接受到了事件:"+event.getClass());
    }
}
代码语言:javascript
复制
package com.boot.event.eventdemo;

import org.springframework.context.ApplicationEvent;

public class MyApplicationEvent extends ApplicationEvent {
    public MyApplicationEvent(Object source) {
        super(source);
    }
}
代码语言:javascript
复制
package com.boot.event.eventdemo;

import org.springframework.context.ApplicationListener;

//第二种方式 @Component
public class MyApplicationListener implements ApplicationListener<MyApplicationEvent> {

    @Override
    public void onApplicationEvent(MyApplicationEvent event) {
        System.out.println("接受到了事件:"+event.getClass());
        System.out.println("接受到了事件:"+event.getSource());
    }
}

application.properties

代码语言:javascript
复制
#第三种方式 
context.listener.classes=com.boot.event.eventdemo.MyApplicationListener

使用第四种方式配置监听器的打印结果:

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-10-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档