Trước đây hỏi và answered here:
Buried trong phần Minimize Mutability của Best Practices Guice, bạn sẽ tìm thấy hướng dẫn này:
Lớp con phải gọi super()
với tất cả các phụ thuộc. Điều này làm cho tiêm xây dựng cồng kềnh, đặc biệt là khi các cơ sở tiêm thay đổi lớp học.
Trên thực tế, đây là cách để làm điều đó bằng tiêm constructor:
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);
}
}
Nguồn
2012-02-06 17:19:36
Là nó thực sự như thế nào các lớp được định nghĩa? Bạn có thể sửa đổi mã nguồn của ba lớp này hay không? Bạn có quyền truy cập vào setter cho trường màu trong các lớp con không? –