我可以在 Spring Boot 中通过这种方式使用 Event bus 吗?

时间:2021-06-30 10:33:38

标签: java spring spring-boot guava greenrobot-eventbus

我在 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方法是否可以正常工作?

0 个答案:

没有答案
相关问题