博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring 事件Application Event
阅读量:7113 次
发布时间:2019-06-28

本文共 2123 字,大约阅读时间需要 7 分钟。

hot3.png

自定义事件

import org.springframework.context.ApplicationEvent;/** * @author Kevin * @description 自定义事件 * @date 2016/6/30 */public class DemoEvent extends ApplicationEvent {    private String msg;    public DemoEvent(Object source, String msg) {        super(source);        this.msg = msg;    }    public String getMsg() {        return msg;    }    public void setMsg(String msg) {        this.msg = msg;    }}

事件监听器

import org.springframework.context.ApplicationListener;import org.springframework.stereotype.Component;/** * @author Kevin * @description 事件监听器 * @date 2016/6/30 */@Componentpublic class DemoListener implements ApplicationListener
{ @Override public void onApplicationEvent(DemoEvent demoEvent) { String msg = demoEvent.getMsg(); System.out.println("DemoListener接收到了DemoPublisher发布的消息:" + msg); }}

事件发布类

import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.ApplicationContext;import org.springframework.stereotype.Component;/** * @author Kevin * @description 事件发布类 * @date 2016/6/30 */@Componentpublic class DemoPublisher {    // 注入applicationContext用来发布事件    @Autowired    ApplicationContext applicationContext;    // 发布事件    public void publish(String msg) {        applicationContext.publishEvent(new DemoEvent(this, msg));    }}

配置类

import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;/** * @author Kevin * @description 配置类 * @date 2016/6/30 */@Configuration@ComponentScan("ch02.event")public class EventConfig {}

运行

import org.springframework.context.annotation.AnnotationConfigApplicationContext;/** * @author Kevin * @description * @date 2016/6/30 */public class Main {    public static void main(String[] args) {        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class);        DemoPublisher demoPublisher = context.getBean(DemoPublisher.class);        demoPublisher.publish("this is a application event");        context.close();    }}

结果

事件监听类将得到输出信息

转载于:https://my.oschina.net/kevinair/blog/703265

你可能感兴趣的文章
Apress 出版社电子书
查看>>
JSP页面
查看>>
vuejs全局api概念
查看>>
超简单,安卓模拟器手动root
查看>>
android自定义view
查看>>
SQL日志文件的作用
查看>>
SQL注入原理 手工注入access数据库
查看>>
算24 (递归)
查看>>
方便查看 linux/include/asm/system.h
查看>>
sql中的!=判断的注意事项
查看>>
作业3(吴雪蕾)
查看>>
Stack Overflow大揭密:哪一种程序员工资最高?
查看>>
C# 链表 --增 -删-反转-删除最小值
查看>>
爬取全部的校园新闻
查看>>
JavaScriptCore
查看>>
union
查看>>
banner 跟随鼠标呈现视差效果
查看>>
linux给用户添加sudo权限
查看>>
前端基础(6)easyUI
查看>>
我有我的方向
查看>>