欢迎光临我的博客查看最新文章: https://river106.cn
Spring Event是Spring的事件通知机制,可以将相互耦合的代码解耦,从而方便功能的修改与添加。Spring Event是观察者模式的一个具体实现。
Spring Event包含事件(ApplicationEvent)、监听器(ApplicationListener)和事件发布(publishEvent)操作。
Spring Event的相关API在spring-context包中;
实现Spring事件机制主要有4个类:
ApplicationEvent:事件,每个实现类表示一类事件,可携带数据。
ApplicationListener:事件监听器,用于接收事件处理时间。
ApplicationEventMulticaster:事件管理者,用于事件监听器的注册和事件的广播。
ApplicationEventPublisher:事件发布者,委托ApplicationEventMulticaster完成事件发布。
以下示例中使用SpringBoot。
org.springframework.boot
spring-boot-starter-parent
2.1.3.RELEASE
org.springframework.boot
spring-boot-starter-web
Spring提供了事件抽象类ApplicationEvent,继承该抽象类即可。
import org.springframework.context.ApplicationEvent;
@Setter
@Getter
public class MsgEvent extends ApplicationEvent {
private String message;
public MsgEvent(String message) {
super(message);
this.message = message;
}
}
1、可以直接使用ApplicationEvent.publishEvent(ApplicationEvent);
@Autowired
private ApplicationContext applicationContext;
applicationContext.publishEvent(ApplicationEvent);
2、通过ApplicationEventPublisher.publishEvent(ApplicationEvent);
直接注入
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
applicationEventPublisher.publishEvent(ApplicationEvent)
实现接口
@Service
public class PublishEvent implements ApplicationEventPublisherAware {
public static ApplicationEventPublisher eventPublisher = null;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
eventPublisher.publishEvent("事件消息");
}
}
处理发布的事件
1、通过实现接口ApplicationListener
@Component
public class MsgEventListener implements ApplicationListener<MsgEvent> {
@Override
public void onApplicationEvent(TestEvent event) {
// 事件处理
System.out.println("监听到消息: " + event.getMessage());
}
}
2、使用@EventListener注解
@Component
public class MsgEventListener {
@Order(5)
@EventListener
public void listener(MsgEvent event) {
System.out.println("注解监听到数据:" + event.getMessage());
}
}
如果有多个监听器,可以通过@Order注解指定监听器执行顺序,@Order中value的值越小,越先执行;
事件监听器默认是同步执行的,如果想要异步执行,可以添加@Async注解(启动类上加@EnableAsync),实际业务开发中要注意@Async的使用。
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan("cn.river.spring.event")
public class ApplicationListenerDemo {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ApplicationListenerDemo.class);
context.publishEvent("123123");
MsgEvent msgEvent = new MsgEvent("发送短信");
context.publishEvent(msgEvent);
}
}