目录
2.1 定义事件
2.1.1 通过ApplicationContext发布消息
2.1.2 通过ApplicationEventPublisher发布消息
2.2.1 通过实现ApplicationListener接口订阅消息
一、场景
我们生活中登陆一些APP的时候会收到短信和PUSH通知,在系统内部还会有一些记录登陆日志等处理,伪代码如下:
public boolean doLogin() {
log.info("login! send LoginEvent");
sendSms();
sendPush();
doLog();
return true;
}
可以发现通知逻辑和主业务逻辑耦合严重;如何解耦呢?下面我们看一下使用SpringEvent 进行解耦。
二、Spring Event使用
Spring的应用上下文支持Bean之间基于事件的通信,发送者P OJO只需要发送事件即可,无须知道接收者是谁,可以存在多个事件接收者。使用步骤如下:
- 定义事件
- 发布事件
- 监听事件
2.1 定义事件
在Spring 中定一个事件必须继承ApplicationEvent类
@ToString
@Getter
@Setter
public class LoginEvent extends ApplicationEvent {
Long userId;
public LoginEvent(Long userId, Object source) {
super(source);
this.userId = userId;
}
}
2.2 发布消息
发布消息可以使用ApplicationContext或ApplicationEventPublisher 调用 publishEvent 方法进行发布消息
2.1.1 通过ApplicationContext发布消息
@Service
@Slf4j
public class LoginService implements ApplicationContextAware {
private ApplicationContext applicationContext;
public boolean doLogin(