Spring也提供了一套好用的基于观察者模式的事件发布机制,
在Spring中,我们只需要将Spring管理的Bean的方法上面加上@EventListener注解,就可以将其标记为一个观察者,
可以使用ApplicationContext上下文来进行事件通知,
从下面的代码中我们可以看到,
ApplicationContext接口继承了ApplicationEventPublisher接口,可以调用publishEvent来进行事件发布,
给关注该事件的观察者发送消息,实际上ApplicationContext就相当于消息总线。
监听器定义,注意这里要加上@Component注解,可以注意到,这里使用了@Async注解,表示方法是异步执行的,这样就可以实现事件的异步发布通知啦!
当然你可以指定自定义的线程池,如果你也使用的SpringBoot,不要忘记在启动类加上@EnableAsync注解。
定义登录事件
package com.example.eventbus.spring;
import lombok.Data;
/**
* @className: LoginEvent
* @author: czh
* @date: 2023/4/22
* @Description: 定义登录事件
* @version: 1.0.0
**/
@Data
public class LoginEvent {
/**
* 用户id
*/
private Long userId;
/**
* 登录类型
*/
private Integer loginType;
}
事件监听@EventListener
/**
* @className: LoginListener
* @author: czh
* @date: 2023/4/22
* @Description: 事件监听@EventListener
* @version: 1.0.0
**/
@Slf4j
@Component
public class LoginListener {
@EventListener
@Async
public void loginEvent(LoginEvent event) {
log.info("监听到登录事件:" + event);
}
}
获取Spring上下文的工具类,用于事件的发布
/**
* @className: SpringContextHolder
* @author: czh
* @date: 2023/4/22
* @Description: 获取Spring上下文的工具类,用于事件的发布
* @version: 1.0.0
**/
@Component
@Slf4j
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextHolder.applicationContext = applicationContext;
}
}
发布事件
package com.example.eventbus.spring;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
/**
* @className: TestMain
* @author: czh
* @date: 2023/4/22
* @Description: 发布事件
* @version: 1.0.0
**/
@SpringBootTest
public class TestMain {
@Test
public void testEventListener() throws InterruptedException {
LoginEvent event = new LoginEvent();
event.setLoginType(1);
event.setUserId(8142L);
//事件的发布
SpringContextHolder.getApplicationContext().publishEvent(event);
Thread.sleep(100);
}
}
.
.
.
git参考代码: 代码
.
.
.