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

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类中实例化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类构造函数。您可以致电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

oo

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);
  }
}

09-26 02:49