我知道这是一个老问题,但我认为更现代的解决方案是使用Guava的事件总线(我不确定它是否适用于GWT,但你的标题和标签都没有说GWT).
我实际上有一个自定义RabbitMQ简单消息容器,它将自动创建队列绑定,然后收到的消息将分派给Guava EventBus.它令人难以置信的优雅,和卓越的鳞片.
您可以轻松使用DI框架注册订阅者.对于Spring,我创建了BeanPostProcessor,它将自动注册bean @Subscribe
.
下面是Spring BeanPostProcessor:
package com.snaphop.spring;
import java.lang.reflect.Method;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
@Component
public class EventBusBeanPostProcessor implements BeanPostProcessor {
private EventBus eventBus;
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (isApplicable(bean)) {
eventBus.register(bean);
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
protected boolean isApplicable(Object bean) {
for(Method m : bean.getClass().getMethods()) {
if (m.isAnnotationPresent(Subscribe.class))
return true;
}
return false;
}
@Autowired
public void setEventBus(EventBus eventBus) {
this.eventBus = eventBus;
}
}
Run Code Online (Sandbox Code Playgroud)
我敢肯定在Guice做类似的事情是微不足道的.
如果您碰巧已经在使用 Spring,那么 Spring 的一个方便的隐藏特性是ApplicationEventMulticaster接口,这是一个非常简单的 API,用于发布和订阅应用程序生成的事件。实现使用TaskExecutor
框架,这意味着它们可以根据需要同步或异步。此外,每个ApplicationContext
都有一个publishEvent
方法,因此为 Spring 管理的类设置它非常容易。
所以是的,如果您已经在使用 Spring,则无需使用其他实用程序来执行此操作,它已经内置了。
归档时间: |
|
查看次数: |
12461 次 |
最近记录: |