java - 我可以在spring boot中通过这种方式使用事件总线吗?
问题描述
我在 Spring Boot 项目中使用事件总线:
<dependency>
<groupId>org.greenrobot</groupId>
<artifactId>eventbus</artifactId>
<version>3.2.0</version>
</dependency>
我定义了一个事件总线 bean:
@Configuration
public class EventBusConfig {
/**
* event bus bean
*/
@Bean
public EventBus eventBus() {
return new EventBus();
}
}
然后我想注册和注销监听器:
@Component
public class EventSubscribeBeanPostProcessor implements BeanPostProcessor, DisposableBean {
private Set<Object> SET = new HashSet<>();
@Autowired
private EventBus eventBus;
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
Method[] methods = bean.getClass().getMethods();
for (Method method : methods) {
Annotation[] annotations = method.getAnnotations();
for (Annotation annotation : annotations) {
if (annotation.annotationType().equals(Subscribe.class)) {
eventBus.register(bean);
SET.add(bean);
return bean;
}
}
}
return bean;
}
/**
* I want to unregister listener by those code,but I don't know whether it can work correctly?
*/
@Override
public void destroy() throws Exception {
SET.forEach(i -> {
eventBus.unregister(i);
});
}
}
有没有人可以告诉我在 Spring Boot 中使用事件总线的最佳实践是什么?如您所见,我不知道 destroy 方法是否可以正常工作?
解决方案
推荐阅读
- reactjs - Html2Canvas 无法正确捕获谷歌地图元素
- scala - Circe、Tapir 和 JodaTime
- gnuplot - 带有一种不同颜色条的 Gnuplot 框
- excel - 根据另一个工作簿行的编号复制和粘贴
- javascript - 单元测试对话框组件入口组件中的实例事件发射器
- python - 使用 win32evtlog Python 打开特定事件日志
- php - 在第二次出现之前添加文本
在一个字符串中
- actions-on-google - Google Action MEDIA_STATUS 不适用于 STOP 和 PAUSE 事件
- python - 计算两个列表上的 Jaccard 相似度以在 Python 中返回最高相似度的词
- css - 在反应中将div对齐到窗口的右侧