简体   繁体   中英

Can Guice's @Singleton annotation be inherited?

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 ?

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM