问题
I'm using Jersey 1.13 with Spring. I've got a ContextResolver defined like so:
@Provider
public class ThemeSourceContextResolver implements ContextResolver<ThemeSource> {
@Context private HttpServletRequest request;
@Override
public ThemeSource getContext(Class<?> type) {
return new DefaultThemeSource(request);
}
}
<bean id="themeSourceContextResolver" scope="singleton" class="com.example.ThemeSourceContextResolver" />
Is the above valid? Specifically, is it "legal" (or does it make sense) to use the @Context private HttpServletRequest request in a ContextResolver? Since the ContextResolver is a singleton, does Jersey/JAX-RS do some threadlocal proxy magic or something to allow it to have access to the HttpServletRequest of every request?
回答1:
It's not valid. @Context is injected only into JAX-RS resources. ContextResolver<?> has nothing to do with request context, mostly because it's a singleton, as you said.
回答2:
To update this answer for Jersey 2.14:
The answer is now "sometimes". Jersey does indeed do proxy magic for specific @Context variables, namely HttpHeaders, Request, UriInfo and SecurityContext. Your specific case, HttpServletRequest, is not supported.
See https://jersey.java.net/documentation/latest/jaxrs-resources.html#d0e2578.
来源:https://stackoverflow.com/questions/13736627/can-you-use-request-scoped-context-variables-in-a-singleton-contextresolver-in