Post creation initialization of guice singleton [duplicate]

匿名 (未验证) 提交于 2019-12-03 09:14:57

问题:

Is there a way to have guice call a init() method after it has instantiated a singleton? Calling init() inside the constructor is not an option since init() could be overriden by a subclass.

回答1:

You can use `@PostConstruct' in guice when you use the mycila/jsr250 extension. This will cause your init() method to be called right after instantiation.

@PostConstruct void init() {      // ... } 

If you do not can/want to add 3rd party libs for this, I wrote a simple postconstruct module for this as well a while ago:

public enum PostConstructModule implements Module, TypeListener {  INSTANCE;  @Override public void configure(final Binder binder) {     // all instantiations will run through this typeListener     binder.bindListener(Matchers.any(), this); }  /**  * Call postconstruct method (if annotation exists).  */ @Override public <I> void hear(final TypeLiteral<I> type, final TypeEncounter<I> encounter) {     encounter.register(new InjectionListener<I>() {          @Override         public void afterInjection(final I injectee) {             for (final Method postConstructMethod : filter(asList(injectee.getClass().getMethods()), MethodPredicate.VALID_POSTCONSTRUCT)) {                 try {                     postConstructMethod.invoke(injectee);                 } catch (final Exception e) {                     throw new RuntimeException(format("@PostConstruct %s", postConstructMethod), e);                 }             }         }     });    }   } 


回答2:

You can annotate a method in your module with @Inject and then request injection on the module:

class MyModule extends AbstractModule {   @Override public void configure() {     requestInjection(this);   }    @Inject void initMyClass(MyClass instance) {      instance.init();   } } 

See also https://stackoverflow.com/a/24480630/3788176.



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