我是Guice的新手并在Google上搜索此问题,但未能找到满意的答案。
public class X {
private Y y;
public X() {
y = new Y("abc", "xyz");
}
}
public class Y {
private String str1;
private String str2;
public Y(String str1, String str2) {
this.str1 = str1;
this.str2 = str2;
}
}
现在,我想将Y注入到类X的构造函数中。
我确实找到了AssistedInject但不是它的构造函数,其中包含一些参数 由Guice提供,其中一些是由来电者提供的。
在这种情况下,构造函数的所有参数都只由调用者提供。
我该怎么做?
答案 0 :(得分:2)
您可以为此使用绑定注释(或内置@Named
),请参阅Guice FAQ
这为您提供了消除2种相同类型歧义的方法。例如
// in the module
bind(String.class).annotatedWith(Names.named("logical.env.id")).toInstance(System.getProperty("logical.env.id", "UK"));
// in the class
@Inject
public Foo(Bar barInstance, @Named("logical.env.id") String logicalEnvId) {
}
答案 1 :(得分:1)
我确实找到了AssistedInject但不是它的构造函数 其中一些参数由Guice提供,其中一些是 由来电者提供。
正确。
这里,在这种情况下,提供了构造函数的所有参数 仅限来电者。
我该怎么做?
按照您的方式执行:在new Y(...)
构造函数中使用X
。
为什么你想在这种情况下使用Guice?