Can you use request scoped @Context variables in a singleton ContextResolver in JAX-RS?

自作多情 提交于 2019-12-12 01:32:47

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!