问题
So, I have a tomcat 8 + jersey 2.5.1 + weld CDI app that works very well in most cases. Where it fails is that I am unable to intercept jersey resource method calls with a CDI interceptor. This makes sense because a jersey resource class is not a CDI bean. Then, is there any way to make a CDI interceptor work in jersey? Another way to ask this question: Can a CDI bean be used as a Jersey resource?
Thanks!
EDIT: Before I wrote my RESTful resources using Jersey, I had CDI interceptors that were used to begin and commit database transactions. I really need to follow the same or similar pattern to implement this cross-cutting transaction injection in my RESTful jersey resources. That is the main reason for asking this question.
Thanks again!
回答1:
Can a CDI bean be used as a Jersey resource?
Yes, but since Jersey's DI is based on hk2 and not CDI, you need a bridge.
In glassfish such a bridge is realized by the module jersey-gf-cdi
:
<dependency>
<groupId>org.glassfish.jersey.containers.glassfish</groupId>
<artifactId>jersey-gf-cdi</artifactId>
<version>2.6</version>
</dependency>
The module registers itself automatically and works on Tomcat beautifully (assuming you have correctly bootstrapped both Jersey and Weld).
Unfortunately, the versions before 2.6 relies on JNDI only, searching the provider under 'java:comp/BeanManager' which Tomcat does not allow.
A fix for this behaviour is available for 2.6 (a pull request I made some time ago), and falls back on CDI.current().getBeanManager()
.
I tested it on Tomcat 7 and works correctly, should work on Tomcat 8 too.
回答2:
Adam Bien in one presentation recommends that you separate your Service (CDI or EJB) class from your RESTful resources class. His reason was that the RESTful class usually uses the HttpHeaders injected by Jersey yet not available in the CDI or EJB containers. The hazard is that your RESTful classes could be injected a Null reference of HttpHeaders if any CDI client like the JSF framework uses it.
Thanks to your self-answered question. You have just showed a second use case that validates Adam Bien's recommendation.
Simply keep them apart!
来源:https://stackoverflow.com/questions/21295589/cdi-interceptor-injected-into-a-jersey-rs-serviceresource-not-working