我可以通过这种方式在spring boot中使用Event bus?

我在spring boot项目中使用eventbus。

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


StackOverflow:java - Can I use Event bus by this way in spring boot? - Stack Overflow