Bostone
Bostone

Reputation: 37126

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?

Upvotes: 4

Views: 9164

Answers (2)

John Ericksen
John Ericksen

Reputation: 11113

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

Upvotes: 6

tvanfosson
tvanfosson

Reputation: 532435

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

Upvotes: 2

Related Questions