我是一个guice新手,试图找出如何使用FactoryModuleBuilder实现guice中的辅助注入。我咨询了guice java文档来实现FactoryModuleBuilder。在guice中使用FactoryModuleBuilder中的辅助注入 - 工厂注入未完成
我完全按照它在文档中所说的完成了一切。 它不注入工厂。 我提到了这个堆栈溢出问题:Guice AssistedInject won't inject the factory 有同样的问题。 它讨论了构造函数注入问题之前的字段注入。我跟着它,我想使用调用者类调用父类,但我仍然得到空指针异常。这里出了什么问题?
主叫类
public class MAIN {
@Inject private static MyFactory factory;
public static void main(String[] args){
ParentClass newbie = new ParentClass(factory);
}
}
我仍然得到异常:
Exception in thread "main" java.lang.NullPointerException
at com.pkg.ParentClass.<init>(ParentClass.java:19)
at com.pkg.MAIN.main(MAIN.java:10)
父类
public class ParentClass {
private final Foo test;
@Inject
public ParentClass(MyFactory factory){
test = factory.create(new HashMap<String,Object>());
}
}
模块实现:ParentModu勒
public class ParentModule extends AbstractModule{
@Override
protected void configure() {
install(new FactoryModuleBuilder()
.implement(Foo.class, FooImpl.class)
.build(MyFactory.class));
}
}
工厂接口:MyFactory
public interface MyFactory {
Foo create(Map<String,Object> map);
}
类接口:富
public interface Foo{
}
类别:FooImpl
public class FooImpl implements Foo {
private final Map<String,Object> mapA;
@AssistedInject
public FooImpl(@Assisted Map<String,Object> map){
mapA=map;
}
}
感谢弗拉基米尔的帮助,但这仍然没有奏效。它给main类中的createInjector中的javax.inject.Provider提供noClassDefFoundError – sachi1325
@ sachi1325,这是你的类路径的一个问题。 Guice依赖于两个库,aopalliance和javax.inject。最后一个似乎从你的classpath中丢失了。我建议使用maven,你可能不会错过任何传递依赖。 –
感谢弗拉基米尔,它的作品! :) – sachi1325