lundi 8 mai 2017

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

Thanks :)

Aucun commentaire:

Enregistrer un commentaire