我有一个类,并使用常规构造函数创建实例:
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。怎么做?
感谢。
答案 0 :(得分:2)
如果我正确理解你,你只是试图让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
:
<强>富强>
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);
}
}
<强> MyModule的强>
public class MyModule extends AbstractModule {
@Override
protected void configure() {
install(new FactoryModuleBuilder().build(FooFactory.class));
}
}
<强>所有MyApplication 强>
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);
}
}