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?
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();
}
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);
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With