往期精选(欢迎转发~~)
- Java全套学习资料(14W字),耗时半年整理
- 2年经验总结,告诉你如何做好项目管理
- 消息队列:从选型到原理,一文带你全部掌握
- 我肝了三个月,为你写出了GO核心手册
- RPC框架:从原理到选型,一文带你搞懂RPC
- 如何看待程序员35岁职业危机?
- 更多...
借助Spring可以非常简单的实现事件监听机制,本文简单介绍下面向接口与注解@EventListener监听的两种姿势。
事件示例
事件对象
在Spring中,所有的事件需要继承自ApplicationEvent,一个最基础的MsgEvent如下
public class MsgEvent extends ApplicationEvent {
private String msg;
/**
* Create a new {@code ApplicationEvent}.
*
* @param source the object on which the event initially occurred or with
* which the event is associated (never {@code null})
*/
public MsgEvent(Object source, String msg) {
super(source);
this.msg = msg;
}
@Override
public String toString() {
return "MsgEvent{" +
"msg='" + msg + '\'' +
'}';
}
}
接口方式消费
消费事件有两种方式,接口的声明,主要是实现ApplicationListener接口;注意需要将listener声明为Spring的bean对象
@Service
public class MsgEventListener implements ApplicationListener<MsgEvent> {
@Override
public void onApplicationEvent(MsgEvent event) {
System.out.println("receive msg event: " + event);
}
}
注解方式消费
实现接口需要新建实现类,更简单的方法是直接在消费方法上加一个注解@EventListener
@EventListener(MsgEvent.class)
public void consumer(MsgEvent msgEvent) {
System.out.println("receive msg event by @anno: " + msgEvent);
}
这个注解,支持根据Event参数类型进行匹配,即上面的实例中,方法上直接加@EventListener不指定圆括号内部的也没关系
发布事件
前面是消费事件,消费的前提是有事件产生,在Spring中,发布事件主要需要借助ApplicationContext来实现
@Service
@ComponentScan({"com.java.event"})
public class MsgPublisher implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
// 发起事件通知
public void publish(String msg) {
applicationContext.publishEvent(new MsgEvent(this, msg));
}
// 通过注解的方法
@EventListener(MsgEvent.class)
public void consumer(MsgEvent msgEvent) {
System.out.println("receive msg event by @anno: " + msgEvent);
}
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(MsgPublisher.class);
MsgPublisher msgPublisher = context.getBean(MsgPublisher.class);
msgPublisher.publish("louzai");
}
}
说明:
- @ComponentScan是用于扫描Spring的Bean;
- 我把“注解方式消费”直接作为MsgPublisher的方法,主要是为了偷懒,你也可以单独整个类,然后将consumer()作为类的成员方法;
- main()是用于测试,直接通过ApplicationContext拿到MsgPublisher的Bean。
测试
直接执行MsgPublisher的main(),输出结果如下:
receive msg event by @anno: MsgEvent{msg='louzai'}
receive msg event: MsgEvent{msg='louzai'}
后记
因为明天开发要用这个,所以就看了一下同事写的一篇博文,然后简单跑了一下。
最近很少写文章,不是懒,是因为这两周在决策一件非常重要的事情,等结果出来了,再告诉大家。等这件事情尘埃落定后,我还是会继续每周输出1-2篇文章。
欢迎大家多多点赞,更多文章,请关注微信公众号“楼仔进阶之路”,点关注,不迷路~~