我们说我有这个课程:
@Singleton
public class Parent { ... }
和这堂课:
public class Child extends Parent { ... }
在我的Java应用程序中,我的应用程序依赖 Guice 注入来创建对象。如果我创建Child
到Injector.createInstance(Child.class)
的实例,那么该实例将自动成为Singleton(因为父项被注释为Singleton),或者我是否需要显式添加@Singleton
注释到Child
?
答案 0 :(得分:5)
不 - 你也需要注释Child
。您可以设置一个简单的测试来验证它:
public class GuiceTest {
@Singleton
static class Parent {}
static class Child extends Parent{}
static class Module extends AbstractModule {
@Override
protected void configure() {
bind(Parent.class);
bind(Child.class);
}
}
@Test
public void testSingleton() {
Injector i = Guice.createInjector(new Module());
assertNotSame(i.getInstance(Child.class), i.getInstance(Child.class));
}
}