问题
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.
来源:https://stackoverflow.com/questions/32635563/post-creation-initialization-of-guice-singleton