Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guice - how to inject abstract field in parent from child

I have a simple hierarchy like follows:

public abstract class AbsFoo {
    protected AbsBoo boo;
}

public class Foo extends AbsFoo {
    public Foo() {
        boo = new Boo(); // Boo extends AbsBoo
    }
} 

EDIT: Instances of AbsFoo should be created on the fly and may not be fields

Can I replace boo = new Boo() with injection?

like image 249
Bostone Avatar asked Feb 20 '23 10:02

Bostone


2 Answers

Yes:

public abstract class AbsFoo {
    protected AbsBoo boo;
}

public class Foo extends AbsFoo {
    @Inject
    public Foo(Boo boo) {
        super.boo = boo; // Boo extends AbsBoo
    }
} 

Make sure you construct your Foo instance with @Inject or injector.getInstance()

Edit

You can also use a provider to create instances on demand:

@Inject
Provider<Foo> fooProvider

//...

public void doSomething(){
    //need new foo:
    Foo foo = fooProvider.get();
}
like image 116
John Ericksen Avatar answered Mar 02 '23 21:03

John Ericksen


As long as Boo itself isn't abstract you should be able to.

public class Foo extends AbsFoo {

    @Inject
    public Foo( AbsBoo boo ) {
        this.boo = boo;
    }
}

public class FooModule extends AbstractModule {
  @Override 
  protected void configure() {
    bind(AbsBoo.class).to(Boo.class);
    bind(AbsFoo.class).to(Foo.class);
  }
}

public static void main(String[] args) {
    Injector injector = Guice.createInjector(new FooModule());
    AbsFoo foo = injector.getInstance(AbsFoo.class);
    ...
}
like image 40
tvanfosson Avatar answered Mar 02 '23 22:03

tvanfosson