【发布时间】:2013-02-05 20:34:02
【问题描述】:
我正在使用 Guava 创建一个 EventBus 用于发布-订阅消息服务。我也是第一次尝试使用 Guice。我已经阅读了 Guice 教程,并且一直在玩 AbstractModule 和 Binder 类。但是当我离开教程并尝试真正为我的项目工作的那一刻,我就窒息了。
我的项目有一个 EventMonitor,它将有一个 Guice 注入的 Guava 实例 EventBus:
public class EventMonitor {
@Inject
private EventBus guavaEventBus;
// ...
}
在我的应用程序的 Guice/DI/Bootstrapping 代码中,我定义了一个AbstractModule concretion:
public class MyAppModule extends AbstractModule {
@Override
public void configure() {
// Here is where I want to wire together the EventBus to give
// to the EventMonitor.
}
}
最终,我想要一个 EventBus,它通常会像这样构造(在非 Guice 代码中):
ThreadFactory factory = ThreadManager.currentRequestThreadFactory();
Executor executor = Executors.newCachedThreadPool(factory)
EventBus eventBus = new AsyncEventBus(executor);
因为ThreadManager 和Executors 上的两个(看似不可注入的)静态方法,我感到窒息,因为我的参考是EventBus,但实际对象是AsynEventBus;因此我不确定如何绑定它:
// Doesn't work because how does Guice know I'm referencing an AsyncEventBus?!?
bind(EventBus.class).toInstance(executor);
// Doesn't work because now I've lost the ability to pass the
// AsyncEventBus an 'executor' and no-arg ctor is used!
bind(EventBus.class).to(AsyncEventBus.class);
所以我问:考虑到我想构建我的EventBus 的方式,一位身经百战的 Guice 退伍军人将如何在这里连接(使用 ThreadFactory、Executor 和 EventBus)这样在EventMonitor 中,完全配置的EventBus 被正确注入了吗?我想一旦我看到这个更“复杂”的例子,我就会开始透过树木看到森林。提前致谢。
【问题讨论】:
标签: java dependency-injection guice