Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guice field injection not working (returns null)

i am having a problem with null values working with Guice. Nex I show you an example of a similar scenario. I know field injection is a bad practice, but I want it to work like this for a demo

I have concrete class named B (which is the one I want to inject):

class B{

    @Inject
    public B(){}

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

I have an abstract class named A, which has the 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 guice configuration is the following:

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

Thanks :)

like image 255
Lauritz Niklas Avatar asked Sep 16 '25 06:09

Lauritz Niklas


1 Answers

This is what's throwing you off:

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

Delete it. Delete the whole module, in fact—none of the methods you've defined are helping your injection.


When you create a @Provides C method, Guice assumes that you're creating C just the way you'd like it, and will not populate @Inject-annotated fields or call @Inject-annotated methods. However, when C has an @Inject-annotated or public argumentless constructor, Guice will inspect the object and create it according to its @Inject fields and methods, which is the behavior you're looking for.

like image 105
Jeff Bowman Avatar answered Sep 17 '25 19:09

Jeff Bowman