Post guice单例创建初始化
Post creation initialization of guice singleton
有没有办法让 guice 在实例化单例后调用 init() 方法?在构造函数中调用 init() 不是一个选项,因为 init() 可以被子类覆盖。
您可以使用 @Inject
注释模块中的方法,然后在模块上请求注入:
class MyModule extends AbstractModule {
@Override public void configure() {
requestInjection(this);
}
@Inject void initMyClass(MyClass instance) {
instance.init();
}
}
另见 。
当你使用mycila/jsr250 extension时,你可以在guice中使用`@PostConstruct'。这将导致您的 init() 方法在实例化后立即被调用。
@PostConstruct
void init() {
// ...
}
如果你不can/want为此添加第三方库,我刚才也为此写了一个简单的postconstruct module:
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 在实例化单例后调用 init() 方法?在构造函数中调用 init() 不是一个选项,因为 init() 可以被子类覆盖。
您可以使用 @Inject
注释模块中的方法,然后在模块上请求注入:
class MyModule extends AbstractModule {
@Override public void configure() {
requestInjection(this);
}
@Inject void initMyClass(MyClass instance) {
instance.init();
}
}
另见 。
当你使用mycila/jsr250 extension时,你可以在guice中使用`@PostConstruct'。这将导致您的 init() 方法在实例化后立即被调用。
@PostConstruct
void init() {
// ...
}
如果你不can/want为此添加第三方库,我刚才也为此写了一个简单的postconstruct module:
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);
}
}
}
});
}
}