Spring 的监听事件 ApplicationListener 和 ApplicationEvent 用法

spring事件(application event)为Bean与Bean之间的消息通信添加了支持,当一个Bean处理完一个任务之后,希望另一个Bean知道并能做相应的处理,这时我们就需要另外一个Bean监听当前Bean所发送的事件。
spring的事件需要遵循以下流程:
(1)自定义事件:继承ApplicationEvent
(2)定义事件监听器:实现ApplicationListener
(3)使用容器发布事件
下面是demo
事件类

/***
 * 
  * @ClassName(类名)      : DemoEvent(自定义事件)
  * @Description(描述)    : spring的event为bean和bean之间的消息通信提供了支持,可以用一个bean监听当前的bean所发送的事件
  * @author(作者)         :吴桂镇
  * @date (开发日期)      :2017年11月22日 下午3:30:04
  *
 */
public class DemoEvent extends ApplicationEvent{

    private static final long serialVersionUID = 1L;

    private String msg;

    public void sysLog() {
        System.out.println(msg);
    }

    public DemoEvent(Object source,String msg) {
        super(source);
        this.setMsg(msg);
    }

    public String getMsg() {
        return msg;
    }

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

监听类

/***
 * 
  * @ClassName(类名)      : demoListener
  * @Description(描述)    : 事件监听器
  *                     实现ApplicationListener并制定监听的事件类型
  * @author(作者)         :吴桂镇
  * @date (开发日期)      :2017年11月22日 下午3:35:37
  *
 */
@Component
public class demoListener implements ApplicationListener<DemoEvent>{

    /***
     * 对消息进行接受处理
     */
    @Override
    public void onApplicationEvent(DemoEvent event) {
        String msg = event.getMsg();
        System.out.println("demoListener接受到了demoPublisher发布的消息:"+msg);
    }


}

发布类

/***
 * 
  * @ClassName(类名)      : DemoPublisher
  * @Description(描述)    : 事件发布类
  * @author(作者)         :吴桂镇
  * @date (开发日期)      :2017年11月22日 下午3:41:13
  *
 */
@Component
public class DemoPublisher {

    @Autowired
    ApplicationContext context;

    public void published() {
        DemoEvent event = new DemoEvent(this, "发布成功!");
        System.out.println("发部event:"+event);
        context.publishEvent(event);
    }
}

测试类

@Configuration
@ComponentScan({"com.wugz.app"})
public class EventConfig {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class);
        DemoPublisher publisher = context.getBean(DemoPublisher.class);
        publisher.published();
        context.close();
    }
}

另附一篇应用的例子

https://www.2cto.com/kf/201701/586004.html

  • 5
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值