users@jersey.java.net

[Jersey] Spring's _at_Autowired field not being set within root resource class

From: Farrukh Najmi <farrukh_at_wellfleetsoftware.com>
Date: Wed, 28 Sep 2011 21:47:33 -0400

I have a top level resource class MyResource in my jersey server that is
correctly being invoked by a jersey client from my junit test.

The junit test starts MyResource in a
org.glassfish.grizzly.http.server.HttpServer, using a
com.sun.jersey.spi.container.servlet.ServletContainer and a
org.glassfish.grizzly.servlet.ServletHandler to set the servlet context,
context-params and init-params.

I then added spring integration to my server using the following blog as
a guide:

http://blogs.oracle.com/enterprisetechtips/entry/jersey_and_spring

Since I do not have an actual servlet but instead have
org.glassfish.grizzly.servlet.ServletHandler I adapted my ServletHandler
as follows:

     public void startServer() {

         // add Jersey resource servlet

         ServletHandler jerseyAdapter = new ServletHandler();

         //Context params
         jerseyAdapter.addContextParameter("contextConfigLocation",
contextLocations);

         //Init params
         
jerseyAdapter.addInitParameter("com.sun.jersey.config.property.packages",
                 packagesToScan);

         jerseyAdapter.setContextPath(myContext);
         jerseyAdapter.setServletInstance(new ServletContainer());

         //Servlet listeners
         
jerseyAdapter.addServletListener("org.springframework.web.context.ContextLoaderListener");
         
jerseyAdapter.addServletListener("org.springframework.web.context.request.RequestContextListener");

         try {

             webServer = GrizzlyServerFactory.createHttpServer(
                     getBaseURI(),
                     jerseyAdapter,
                     false
             );

             webServer.start();
         } catch (Exception ex) {
             System.err.println(ex.getMessage());
         }
     }

So far all is well and I can see that my spring ApplicationContext is
created and the beans defined within are instantiated (good).

Next, I added a field to MyResource where

    * Class is annotated by @Component and @Scope
    * Field foo is annotated with @Autowired


@Path("/rest/events")
*_at_Component
@Scope("request")*
public class MyResource {
*_at_Autowired*
     private Foo foo;

     @Path("all")
     @GET
     public Response allEventsGet() {
*... field foo is null here and autowiring does not seem to be working
(not good) ....*
     }

     public void setFoo(Foo foo) {
         this.foo = foo;
     }
}

Can any one tell me what I am doing wrong that is causing the field foo
to not be auto-wired in MyResource? Looking at the TRACE messages from
spring I can see that the singleton Foo instance was indeed created.
However it never gets injected into the @Autorwired field foo in MyResource.

Thanks for your help.

-- 
Regards,
Farrukh Najmi
Web: http://www.wellfleetsoftware.com