Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 创建安装在当前模块内的另一个模块的guice injector_Java_Dependency Injection_Guice - Fatal编程技术网

Java 创建安装在当前模块内的另一个模块的guice injector

Java 创建安装在当前模块内的另一个模块的guice injector,java,dependency-injection,guice,Java,Dependency Injection,Guice,有一个需要许多实现才能绑定到它的接口。 由于许多限制(可能看起来不太好,请忽略该设计),选择以下设计 是否可以为当前模块中安装的另一个模块创建喷油器,同时仍为当前模块运行configure()方法 public class CurrentModule extends AbstractModule{ @Override protected void configure() { install(new OtherModule()

有一个需要许多实现才能绑定到它的接口。 由于许多限制(可能看起来不太好,请忽略该设计),选择以下设计

是否可以为当前模块中安装的另一个模块创建喷油器,同时仍为当前模块运行configure()方法

public class CurrentModule extends AbstractModule{


         @Override
         protected void configure() {
                install(new OtherModule());
                final someInterface getInstance = methodToGetInstance();
                bind(SomeInterface.class).to(getInstance);

         }


         public SomeInterface methodToGetInstance() {
          Injector injector = Guice.createInjector(new OtherModule());
          return new ClassImplementingSomeInterface(injector.getInstance(dependency)); 
       }
}

是的,通过提供者方法可以实现您的要求。这是你应该做的:

class CurrentModule extends AbstractModule {

  @Override protected void configure() {
    install(new OtherModule());

    // Optional, but it's good to write it if the dependency becomes missing from OtherModule.
    requireBinding(DependencyFromOtherModule.class);
  }

  @Singleton
  @Provides SomeInterface createSomeInterface(DependencyFromOtherModule dependency) {
    return new ClassImplementingSomeInterface(dependency);
  }

}