Can Guice's @Singleton annotation be inherited?

自作多情 提交于 2019-12-11 02:32:17

问题


Let's say that I have this class:

@Singleton
public class Parent { ... }

and this class:

public class Child extends Parent { ... }

in my Java app, and my app relies on Guice injection to create objects. If I create an instance of Child through Injector.createInstance(Child.class), wiill that instance be a Singleton automatically (because the parent was annotated as a Singleton), or do I need to explicitly add the @Singleton annotation to Child?


回答1:


Nope - you'd need to annotate Child as well. You can set up a simple test to verify this like:

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));
  }

}


来源:https://stackoverflow.com/questions/13015831/can-guices-singleton-annotation-be-inherited

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!