Guice的@Singleton注释可以继承吗? [英] Can Guice's @Singleton annotation be inherited?

查看:58
本文介绍了Guice的@Singleton注释可以继承吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说我有这个课程:

@Singleton
public class Parent { ... }

和此类:

public class Child extends Parent { ... }

在我的Java应用程序中,我的应用程序依靠 Guice 注入来创建对象。如果通过 Injector.createInstance(Child.class)创建 Child 的实例,该实例将自动成为Singleton (因为父级被注释为Singleton),或者我需要将 @Singleton 注释显式添加到 Child

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?

推荐答案

不是-您还需要注释 Child 。您可以设置一个简单的测试来验证这一点,例如:

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

}

这篇关于Guice的@Singleton注释可以继承吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆