Using @Context in JAX-RS Provider to provide context information to CDI beans

ε祈祈猫儿з 提交于 2019-12-10 23:58:16

问题


I have some web-service (JAX-RS, WildFly 9, Resteasy)

@RequestScoped
public class SomeService{
// operations
}

Now I want to extract context information like user agent, which can be done using

@Context
private HttpHeaders httpHeaders;

It seems only be possible to inject this context in JAX-RS-related classes, but not in CDI beans called by the webservice. It is possible to put it into the webservice but this clutters the service with stuff not related to the core response of the service.

After some searching, I ended up using the javax.ws.rs.ext.Provider annotation. It seems that the produced ContextInformation object can then be used in other CDI-beans, not just in JAX-RS beans.

@Provider
public class ContextInformationProducer {
    @Produces
    @RequestScoped
    public ContextInformation create() {
        ContextInformation contextInformation = new ContextInformation();
        contextInformation.setBrowserUserAgent(httpHeaders.getHeaderString("User-Agent"));
    }

The question is if this is good practice? Or is it just a coincidence that this works? If it is not good practice, how can I do that in a better way? After looking at What does Provider in JAX-RS mean?, I am not sure if I am 'extending and customizing the JAX-RS runtime'. Should this used by application developers?

来源:https://stackoverflow.com/questions/33553472/using-context-in-jax-rs-provider-to-provide-context-information-to-cdi-beans

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