Hi Francois,
@Resource is not injected, since Jersey doesn't know that you want this
bean to be managed by the container.
You can try to mark your resource "MyResource" with @ManagedBean - then
@Resource fields should be injected.
See managed beans webapp example:
https://github.com/jersey/jersey/tree/927b4d0605aeb119d15e9623dab65c8aec2c8e20/examples/managed-beans-webapp
, concretely this class:
https://github.com/jersey/jersey/blob/927b4d0605aeb119d15e9623dab65c8aec2c8e20/examples/managed-beans-webapp/src/main/java/org/glassfish/jersey/examples/managedbeans/resources/ManagedBeanSingletonResource.java
Hope it helps,
Pavel
On 11/07/16 23:35, Francois Ross wrote:
> Hi,
>
> *How come @Resource annotations get picked up by servlets but not by
> Jersey resources?*
> I've been struggling to inject a DataSource via @Resource for a few
> hours with no success so far (I got lost along the way reading about
> jersey CDI, Weld, HK2, ...). I've set up a small Eclipse project on
> GitHub showing the behavior (see here
> <https://github.com/fross/jersey-resource-not-injected/tree/master/src/demo>).
>
> I'm using:
>
> * Tomcat 7 (dynamic web module version 3.0).
> * a H2 data source configured in META-INF/context.xml
> * jersey-container-servlet 2.23.1
>
> Any help or explanation would be greatly appreciated (I'm a
> desktop/embedded software developer).
>
> importjavax.annotation.Resource;
> importjavax.sql.DataSource; importjavax.ws.rs.GET;
> importjavax.ws.rs.Path; importjavax.ws.rs.Produces;
> importjavax.ws.rs.core.MediaType;
> importjavax.ws.rs.core.Response; @Path("/")
> publicclassMyResource { @Resource(name ="jdbc/myDatabase")
> privateDataSource_dataSource;
> @GET_at_Produces(MediaType.TEXT_PLAIN) publicResponsedoGet()
> { returnResponse.ok() .entity("jersey -> dataSource?
> "+(_dataSource !=null)) *// jersey -> dataSource? false*.build(); } }
>
> importjava.io.IOException;
> importjavax.annotation.Resource;
> importjavax.servlet.ServletException;
> importjavax.servlet.annotation.WebServlet;
> importjavax.servlet.http.HttpServlet;
> importjavax.servlet.http.HttpServletRequest;
> importjavax.servlet.http.HttpServletResponse;
> importjavax.sql.DataSource; @WebServlet(urlPatterns ={
> "/servlet"}) publicclassMyServlet extendsHttpServlet {
> @Resource(name ="jdbc/myDatabase")
> privateDataSource_dataSource;
> @OverrideprotectedvoiddoGet(HttpServletRequestreq,
> HttpServletResponseresp) throwsServletException,
> IOException{ try{ _dataSource.getConnection(); }
> catch(Exceptione) { e.printStackTrace(); }
> resp.setContentType("text/plain");
> resp.getWriter().write("servlet -> dataSource?
> "+(_dataSource !=null)); *// servlet -> dataSource? true*} }
>