[英]Guice: Inject class with constructor with own parameters?
我對 Guice 有疑問。 我想用一個例子來說明這一點。 我想總是動態地傳遞這個構造函數的參數,例如 new Test("bob", 765);。 我還希望 Guice 注入一些字段(比如這里的 SomeOtherObject)。 我怎樣才能做到這一點? 提前致謝!
public class Test {
private String name;
private int id;
//Needs to be injected by Guice
@Inject
SomeOtherObject object;
public Test(String name, int id) {
this.name = name;
this.id = id;
}
}
Guice 的AssistedInject功能是處理這個問題的好方法。
基本上,您定義一個工廠來獲取Test
對象:
public interface TestFactory {
public Test create(String name, int id);
}
使用@Assisted
注釋增強Test
類的@Inject
構造函數:
public class Test {
@Inject
public Test(SomeOtherObject object, @Assisted String name, @Assisted int id) {
this.object = object;
this.name = name;
this.id = id;
}
}
然后在模塊的配置中使用FactoryModuleBuilder
:
install(new FactoryModuleBuilder().build(TestFactory.class));
而不是直接構造Test
s,而是注入一個TestFactory
並使用它來創建Test
s:
public class OtherThing {
@Inject
TestFactory factory;
public Test doStuff(Stirng name, int id) {
return factory.create(name, id);
}
}
注意:現在查看文檔,似乎AutoFactory已被引入作為執行此操作的首選方式,並且可能更簡單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.