我想知道如何将单例绑定到提供程序中的参数。
IE:
@Singleton
public class RunButtonController{
@Inject
public RunButtonController(EventBus eventbus){ ... }
public JComponent getView(){
return view;
}
...
}
public class UncaughtExceptionController{
@Inject
public UncaughtExceptionController(
EventBus eventBus, ...,
@Named(DefaultExceptionViewKey) JComponent defaultView)
{ ... }
...
}
public class GUIController{
//another consumer of RunButtonController, arguably the "main" consumer.
@inject
public GUIController(RunButtonController runButtonController,
UncaughtExceptionController uncaughtExceptionController, ...)
{ ... }
...
}
public class Bootstrapper{
public static void main(String[] args){
Injector injector = Guice.createInjector(new OptipModule());
GUIController controller = injector.getInstance(GUIController.class);
}
private static class OptipModule extends AbstractModule{
@Override
protected void configure() {
bind(EventBus.class).toInstance(new EventBus("OPTIPGlobalEventBus"));
bind(JFrame.class).to(GUIView.class);
}
@Provides @Named(DefaultExceptionViewKey)
public JComponent getFrom(RunButtonController runButtonController){
return runButtonController.getView();
}
}
}
在我的构造函数上放置一个断点RunButtonController
,我可以看到它始终被实例化两次。我希望它只被实例化一次,我想
defaultExceptionViewProvider == runButtonController
成为true
.
我已经相当广泛地使用了 Castle Windsor,但这是我使用过的唯一 IOC 容器,所以我对 guice 很陌生。我在整个地方都看到了访问者行为的残余,guice 的文档清楚地表明,类的定义行为(即,实例一次,使用这个实例,使用这个工厂,......)不会持续超过为其配置的模块。我想说我看到它写了当你使用时@Provides
,guice 会为你创建一个子模块,所以大概我需要做的是告诉这个孩子@Provides-生成的模块'嘿,这个类是一个单例我正在解决它,所以就在这里!不要使用你自己的!
我认为我正在以错误的方式处理这个框架。我一直在破坏注释并进行调试,但也许我真正需要做的是花几个小时阅读一个好的教程,不幸的是我找不到。JavaDoc 有示例,并且网页发布了它们,但是它们给您的上下文很少,因此,在阅读了三遍@Assisted 上的文章后,我仍然不明白它(也许这就是我应该使用的?)加分对于指向特别详细的博客作者和他页面上的guice条目的人。
沿着这些思路,并且非常离题,我想知道我试图将“嘿,你的默认通知区域是其他人的视图”推送到我的 IOC 容器中会产生什么后果。这可能是领域逻辑吗?我真的不想UnhandledExceptionController
知道它的视图是由 a 提供的RunButtonController
,同样我不想RunButtonController
知道它的视图被用于除被印在视图树上之外的任何东西。
谢谢阅读!