What do I do with Guice when I need to call a parent constructor that is also injectable? e.g. I have an abstract parent class that has a constructor that is injected with a
Buried in the Minimize Mutability section of the Guice Best Practices, you'll find this guideline:
Subclasses must call
super()
with all dependencies. This makes constructor injection cumbersome, especially as the injected base class changes.
In practice, here's how to do it using constructor injection:
public class TestInheritanceBinding {
static class Book {
final String title;
@Inject Book(@Named("GeneralTitle") String title) {
this.title = title;
}
}
static class ChildrensBook extends Book {
@Inject ChildrensBook(@Named("ChildrensTitle") String title) {
super(title);
}
}
static class ScienceBook extends Book {
@Inject ScienceBook(@Named("ScienceTitle") String title) {
super(title);
}
}
@Test
public void bindingWorked() {
Injector injector = Guice.createInjector(new AbstractModule() {
@Override protected void configure() {
bind(String.class).
annotatedWith(Names.named("GeneralTitle")).
toInstance("To Kill a Mockingbird");
bind(String.class).
annotatedWith(Names.named("ChildrensTitle")).
toInstance("Alice in Wonderland");
bind(String.class).
annotatedWith(Names.named("ScienceTitle")).
toInstance("On the Origin of Species");
}
});
Book generalBook = injector.getInstance(Book.class);
assertEquals("To Kill a Mockingbird", generalBook.title);
ChildrensBook childrensBook = injector.getInstance(ChildrensBook.class);
assertEquals("Alice in Wonderland", childrensBook.title);
ScienceBook scienceBook = injector.getInstance(ScienceBook.class);
assertEquals("On the Origin of Species", scienceBook.title);
}
}