我是Guice的新手,所以我想了解AssistedInject。 我有一个非常简单的项目:
我想要注入的类:
public class I1 {
}
辅助注射类:
public interface ICla {
}
public class Cla implements ICla{
public Integer t;
public I1 i;
@Inject
public Cla(Integer t, @Assisted I1 i) {
this.t = t;
this.i = i;
}
}
厂
public interface IClaFactory {
Cla create(Integer t);
}
主要课程:
public class Main {
public static void main(String[] args) {
Injector injector = Guice.createInjector(new Module());
IClaFactory factory = injector.getInstance(IClaFactory.class);
}
private static class Module extends AbstractModule {
protected void configure() {
install(new FactoryModuleBuilder()
.implement(ICla.class, Cla.class).build(IClaFactory.class));
}
}
}
但它仍然不起作用,我不明白,我错了?
Exception in thread "main" com.google.inject.CreationException: Unable to create injector, see the following errors:
1) No implementation for ru.test.factory.I1 annotated with @com.google.inject.assistedinject.Assisted(value=) was bound.
while locating ru.test.factory.I1 annotated with @com.google.inject.assistedinject.Assisted(value=)
for parameter 1 at ru.test.factory.Cla.<init>(Cla.java:11)
at ru.test.factory.IClaFactory.create(IClaFactory.java:1)
at com.google.inject.assistedinject.FactoryProvider2.initialize(FactoryProvider2.java:660)
at com.google.inject.assistedinject.FactoryModuleBuilder$1.configure(FactoryModuleBuilder.java:335) (via modules: ru.test.Main$Module -> com.google.inject.assistedinject.FactoryModuleBuilder$1)
2) Could not find a suitable constructor in java.lang.Integer. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private.
at java.lang.Integer.class(Integer.java:52)
while locating java.lang.Integer
for parameter 0 at ru.test.factory.Cla.<init>(Cla.java:11)
at ru.test.factory.IClaFactory.create(IClaFactory.java:1)
at com.google.inject.assistedinject.FactoryProvider2.initialize(FactoryProvider2.java:660)
at com.google.inject.assistedinject.FactoryModuleBuilder$1.configure(FactoryModuleBuilder.java:335) (via modules: ru.test.Main$Module -> com.google.inject.assistedinject.FactoryModuleBuilder$1)
答案 0 :(得分:2)
你@Assisted
- 错误的参数:&#34; help&#34; with是工厂界面中定义的参数。在这种情况下,它是您的Integer
,而不是您的I1
。
这将有效:
@Inject
public Cla(I1 i, @Assisted Integer t) {
this.t = t;
this.i = i;
}