如何使用 Guice 模块实例化 class 中的多个字段之一?

How to use Guice Module to instantiate one of multiple fields in a class?

我有一个 class,并使用常规构造函数创建一个实例:

class Foo {
  String fooName;
  Bar barObject;
  ExternalService externalService;

  Foo(String fooName, Bar barObject, Service someService){
    this.fooName = fooName;
    this.barObject = barObject;
    this.externalService = externalService;
    //call to super
    }
}


class MyApplication {
  //instantiate ExternalService 
  ...

  Foo foo = new Foo(String fooName, Bar barObject, ExternalService externalService);
}

ExternalService 归其他人所有,他们现在提供了一个 Guice 模块(类似于 ExternalServiceModule)。我怎样才能使用这个模块 在我的 Foo class?

中实例化 ExternalService

我正在尝试

class Foo {
  String fooName;
  Bar barObject;
  ExternalService externalService;

  @Inject
  Foo(String fooName, Bar barObject, Service someService){
    this.fooName = fooName;
    this.barObject = barObject;
    this.externalService = externalService;
    //call to super
  }
}

class MyApplication {
    ...
  ExternalServiceModule ecm = new ExternalServiceModule();
  Injector injector = Guice.createInjector(ecm);
  Foo foo = injector.getInstance(Foo.class);
}

但显然我没有以第二种方式传递 fooName 和 barObject。如何做到这一点?

谢谢。

如果我没理解错的话,您只是想获取 ExternalService 的实例以传递给您的 Foo class 构造函数。您可以致电 injector.getInstance(ExternalService.class):

class MyApplication {
  Injector injector = Guice.createInjector(new ExternalServiceModule());
  ExternalService externalService = injector.getInstance(ExternalService.class);
  Bar someBar = new Bar();
  Foo foo = new Foo('someName', someBar, externalService);
}

但是由于您使用的是 Guice,您可能正在寻找 assisted inject:

public class Foo {
  private String fooName;
  private Bar barObject;
  private ExternalService externalService;

  @Inject
  public Foo(
      @Assisted String fooName,
      @Assisted Bar barObject,
      ExternalService externalService) {
    this.fooName = fooName;
    this.barObject = barObject;
    this.externalService = externalService;
  }

  public interface FooFactory {
    Foo create(String fooName, Bar barObject);
  }
}

我的模块

public class MyModule extends AbstractModule {
  @Override
  protected void configure() {
    install(new FactoryModuleBuilder().build(FooFactory.class));
  }
}

我的应用程序

public class MyApplication {

  public static void main(String[] args) {
    Injector injector = Guice.createInjector(
        new ExternalServiceModule(), new MyModule());
    FooFactory fooFactory = injector.getInstance(FooFactory.class);

    Bar someBar = new Bar();
    Foo foo = fooFactory.create("SomeName", someBar);
  }
}