Guice field injection not working (returns null)

I have a problem with null values ​​working with Guice. Nex I'll show you an example of a similar scenario. I know field injection is bad practice but I want it to work like this for demonstration

I have a specific class named B (which I want to inject):

class B{

    @Inject
    public B(){}

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

      

I have an abstract class named A that has class B (the one I want to inject by field injection):

abstract class A{

    @Inject
    protected B b;

}

      

Now, another concrete class named C that extends A :

class C extends A{

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

      

My lip configuration is as follows:

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();
    }
}

      

Then I have a test with Spock:

@UseModules(ConfigModule)
class Test extends Specification{

    @Inject
    public C c;

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

      

Thank:)

+3


source to share


1 answer


This is what throws you out:

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

      

Delete it. Actually remove the entire module - none of the methods you have defined help your injection.




When you create a method @Provides C

, Guice assumes that you create C the way you like, and that you don't fill in @Inject

-undefined fields or call @Inject

-independent methods. However, when C has a @Inject

-annotated or public constructor with no arguments, Guice will inspect the object and create it according to its fields and methods @Inject

, which is the behavior you are looking for.

+3


source







All Articles