后期创建初始化guice singleton [英] Post creation initialization of guice singleton
本文介绍了后期创建初始化guice singleton的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法让guice在实例化单例后调用init()方法?在构造函数中调用init()不是一个选项,因为init()可以被子类覆盖。
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.
推荐答案
你可以使用当你使用 mycila / jsr250扩展时,`@ PostConstruct'就会出现问题。这将导致在实例化后立即调用init()方法。
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() {
// ...
}
如果你不能/想要为此添加第三方库,我写了一个简单的 postconstruct模块对于此以及不久前:
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);
}
}
}
});
}
}
这篇关于后期创建初始化guice singleton的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文