Guice AssistedInject不会注入工厂

我正在尝试使用Guice 3.0 AssistedInject ,它不会实例化工厂。

SSCCE代码:

家长class

 public class ParentClass() { @Inject private MyFactory myFactory; private final Foo foo; private final Bar bar; public ParentClass() { if(myFactory == null) System.err.println("Error: I should have injected by now!"); foo = myFactory.create(new Map()); // etc. } } 

工厂界面

 public interface MyFactory { Foo create(Map mapA); Bar create(Map mapB, Map mapC); } 

 public class ParentModule extends AbstractModule { @Override protected void configure() { install(new FactoryModuleBuilder() .implement(Foo.class, FooImpl.class) .implement(Bar.class, BarImpl.class) .build(MyFactory.class)); } 

FooImpl

 public class FooImpl implements Foo { private final Map mapA; @AssistedInject public FooImpl(@Assisted Map mapA) { this.mapA = mapA; } } 

BarImplFooImpl非常相似。 这里出了什么问题? 另请注意,我在这里尝试了@AssistedInject@Inject ,都会导致错误。

输出:

 Error: I should have injected by now! Exception in thread "main" com.google.inject.ProvisionException: Guice provision errors: 1) Error injecting constructor, java.lang.NullPointerException at ParentClass.(ParentClass.java:7) while locating com.my.package.ParentClass 1 error at com.google.inject.internal.InjectorImpl$4.get(InjectorImpl.java:987) at com.google.inject.internal.InjectorImpl.getInstance(InjectorImpl.java:1013) at com.my.package.ParentMain.main(ParentMain.java:16) Caused by: java.lang.NullPointerException at com.my.package.ParentClass.(ParentClass.java:9) at com.my.package.ParentClass$$FastClassByGuice$$d4b3063a.newInstance() at com.google.inject.internal.cglib.reflect.$FastConstructor.newInstance(FastConstructor.java:40) ... 8 more 

注意,第9行是第一次调用myFactory.create()

根据Guice的javadoc , 构造注入进行场注入。

我假设你的ParentClass实例是由Guice创建的。 当你的ParentClass的构造函数被执行时,它的myFactory字段还没有被注入。

两件事情。 要在构造函数中使用注入,必须使用构造函数注入:

 public class ParentClass { private final Foo foo; private final Bar bar; @Inject public ParentClass(MyFactory myFactory) { if(myFactory == null) System.err.println("Error: I should have injected by now!"); this.foo = myFactory.create(new HashMap()); this.bar = myFactory.create(new HashMap(), new HashMap()); } } 

此外,由于您的工厂有两个相同类型的参数,您需要命名它们:

 public interface MyFactory { Foo create(Map mapA); Bar create(@Assisted("B") Map mapB, @Assisted("C") Map mapC); } 

 public class BarImpl implements Bar { private final Map mapA; private final Map mapB; @AssistedInject public BarImpl(@Assisted("B") Map mapA, @Assisted("C") Map mapB) { this.mapA = mapA; this.mapB =mapB; } } 
Interesting Posts