可能重复:
Guice with parents
class Book{string title;}
class ChildrensBook extends Book{}
class ScienceBook extends Book{}
我想将书名注入子类中,例如,childrensBook
应该被赋予标题"爱丽丝梦游仙境"并且ScienceBook
应该得到"关于物种起源"。我如何用Guice实现这一目标?
(请注意,我不想覆盖子类中的title
字段)
答案 0 :(得分:5)
之前曾问及answered here:
埋藏在Guice最佳实践的Minimize Mutability部分,您会找到以下指南:
子类必须使用所有依赖项调用
super()
。这使得 构造函数注入繁琐,特别是作为注入基础 班级变化。
在实践中,以下是使用构造函数注入的方法:
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);
}
}
答案 1 :(得分:0)
您最好的选择可能是使用不同的参数注释编写子类构造函数 - 类似于
class ChildrensBook extends Book {
@Inject ChildrensBook (@AliceInWonderland String title) {
super(title);
}
}