Guice 字段注入不起作用(returns null)

Guice field injection not working (returns null)

我在使用 Guice 时遇到空值问题。接下来,我将向您展示一个类似场景的示例。 我知道字段注入是一种不好的做法,但我希望它在演示中像这样工作

我有一个名为 B 的混凝土 class(这是我要注入的那个):

class B{

    @Inject
    public B(){}

    public void fooMethod(){
        System.out.println("foo!")
    }
}

我有一个名为 A 的摘要 class,其中有 class B(我想通过字段注入来注入):

abstract class A{

    @Inject
    protected B b;

}

现在另一个名为 C 的混凝土 class 扩展了 A:

class C extends A{

    public void barMethod(){
        System.out.println("is b null? " + (b==null)); // is true
    }
}

我的guice配置如下:

class ConfigModule extends AbstractModule {

    @Override
    protected void configure(){
        // bind(B.class) // I have also tried this
    }

    @Provides
    B getB(){
        return new B();
    }

    @Provides
    C getC(){
        return new C();
    }
}

然后我和 Spock 进行测试:

@UseModules(ConfigModule)
class Test extends Specification{

    @Inject
    public C c;

    def "test"() {
        // Here goes the test using:
        c.barMethod();
    }       
}

谢谢:)

这就是让你失望的原因:

@Provides
C getC(){
    return new C();
}

删除它。删除整个模块,事实上 — none 您定义的方法正在帮助您的注入。


当您创建 @Provides C 方法时,Guice 假定您正在按照您喜欢的方式创建 C,并且不会填充 @Inject-注释字段或调用 @Inject-注释方法。但是,当 C 有一个 @Inject-注释或 public 无参数构造函数时,Guice 将检查对象并根据其 @Inject 字段和方法创建它,这就是您正在寻找的行为对于.