users@jersey.java.net

SpringServlet support when Spring is not started from a web context?

From: Alex Sherwin <alex.sherwin_at_acadiasoft.com>
Date: Fri, 14 May 2010 08:44:20 -0400

I just noticed when setting up SpringServlet with an embedded Jetty
server started by Spring (which was not started by a web context), that
the SpringServlet will fail to startup, as it makes the assumption that
it can get the information either from the init-param
"contextConfigLocation" or the "default" via
WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());

What I'm doing is using Jetty, like so:

       final ServletContextHandler contextHandler = new
ServletContextHandler(ServletContextHandler.SESSIONS);
       contextHandler.setContextPath(context);
       contextHandler.addServlet(new ServletHolder(springServlet), "/*");
       jettyServer.setHandler(contextHandler);
       jettyServer.start();

My solution was to extend SpringServlet and override initiate like so:

   @Override
   protected void initiate(ResourceConfig rc, WebApplication wa) {
     try {
       wa.initiate(rc, new SpringComponentProviderFactory(rc,
applicationContext));
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
   }

Where my new servlet bean is a Spring Component, which I obtain from the
Spring ApplicationContext, and as such I inject the "applicationContext"
variable in the above method override like so:

@Autowired
   protected ConfigurableApplicationContext applicationContext;

Easy enough solution, however, I feel like Jersey should natively
support Spring in such a way that doesn't REQUIRE it to be started from
a web application context