class TestClass {
@Inject
public TestClass(String arg1, @Assisted String arg2) {
System.out.printf("TestClass(%s, %s)\n", arg1, arg2);
}
}
interface TestFactory {
TestClass makeTestClass(String extraArg);
}
class Main {
@Inject
public TestFactory factory;
public static void main(String[] args) {
Injector i = Guice.createInjector(
new AbstractModule() { @Override protected void configure() {
bind(String.class).toInstance("any string");
install(new FactoryModuleBuilder().build(TestFactory.class));
}}
);
Main m = i.getInstance(Main.class);
m.factory.makeTestClass("assisted");
}
}此代码正确工作,并打印“TestClass(任意字符串,辅助)”。
但医生,我必须叫他
install(new FactoryModuleBuilder()
.implement(TestClassInterface.class, TestClass.class)
.build(TestFactory.class));什么时候以及为什么我必须使用工具()?只有在什么时候才有命名绑定?
发布于 2016-10-20 20:49:38
当工厂方法的返回类型与您希望Guice实例化的类型不同时,您需要使用.implement()。通常,如果工厂方法返回接口类型,则会发生这种情况。您可以使用.implement()告诉Guice它应该创建的具体类类型。
https://stackoverflow.com/questions/40156670
复制相似问题