簡體   English   中英

Guice:使用帶有自己參數的構造函數注入 class?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM