带有ServicEloDADER的GUICE在不使用喷油器的情况下为Plug Ins创建类实例



我的核心应用程序已完成。我能够成功加载模块,但我仍然无法正确使用GUICE在模块中注入依赖项。我的Core App使用Service Loader加载模块,并使用Guice AbstractModule的安装方法安装它们。这是示例代码:(简化)

 @Override
protected void configure() {
    ServiceLoader<IModule> modules = ServiceLoader.load(IModule, ucl);
    for (IModule module : modules) {
        install(module);
    }
} 

每个模块都实现了扩展GUICE模块接口的Imodule接口。让我感到困惑的是,当不建议整个地方都有注射器时,我该如何提供插件的实例(例如,视图的实例)。我阅读了有关@provides注释的信息,我认为这是一个可能的解决方案,但我遇到的另一个问题是其中一些需要注射需要注射。例如,我的插件视图注入插件的实例。考虑到这种情况,我不确定如何使用提供商界面。建议将真正感谢

public PlugIn implements IModule{
    @Override
    public void configure(Binder binder){
        binder.bind(View.class).to(PlugInView.class);
    }
    public View getView(){
        //Should return a view instance
        //Still unsure how to provide this
    }
}
public PlugInView extends View{
   @Inject
   private PlugInView(PlugInController controller){
   //Do stuff with controller
   }
}

好吧,我终于发现了为什么我的方法不起作用。阅读后,似乎为了让Guice注入依赖性,Guice必须是实例化您的课程的人。在我的方法中,我有一个迭代器,该迭代器懒惰地实例化了由服务加载器加载的模块。为了解决该问题,我已经停止从Core App中安装模块。

@Override
protected void configure() {
    ServiceLoader<IModule> modules = ServiceLoader.load(IModule, ucl);
    bind()...//Configure core app bindings
    //Removed this part
    for (IModule module : modules) {
        install(module);
    }
    //Until here
} 

并将每个插件插入自己的喷油器中,以调用自己的配置方法。这种方法似乎给出了每个模块独立的喷油器,我认为这似乎可以接受,因为我希望每个模块都独立。我还喜欢这种方法如何允许我的插件ins不再实现模块接口或扩展抽象模块,从而可以自由选择使用GUICE。

最新更新