问题
I would like to know if the RequestScoped
context is currently active in a method or not.
At the moment, here is what I do :
@Inject private BeanManager beanManager;
public boolean isRequestScopeActive() {
try {
if (beanManager.getContext(RequestScoped.class).isActive()) {
return true;
} else {
return false;
}
} catch (final ContextNotActiveException e) {
return false;
}
}
I think it's a bit heavy to catch a ContextNotActiveException
just to know if a scope is active or not.
Do you have any better way to know the state (active or not) of a context in CDI ?
回答1:
Yeah, the only option we have in CDI 1.0 is to catch the ContextNotActiveException. This actually ends up being a big problem for apps scoped, where the scope implementation is not available for injection. E.g. You can't just @Inject RequestScopedContextImpl rq;
and check the .isActive()
method, because we don't have access to that class without knowing the implementation details.
来源:https://stackoverflow.com/questions/11507109/is-there-a-way-to-know-if-a-state-is-active-without-catching-contextnotactiveexc