users@jersey.java.net

[Jersey] Jersey and Spring (Not Integrated) with no web.xml

From: Robert DiFalco <robert.difalco_at_gmail.com>
Date: Sat, 8 Mar 2014 09:05:00 -0800

I am using Jersey and Spring together. I am not using the integration. I'm
using servlet 3.0 and attempting to create an app with no web.xml. So I
have the following. I am sending my spring ApplicationContext to my
RestConfig because I bind one bean (a JobServiceLocator) to inject into my
Rest Resources (they typically just delegate their requests to the job
server).

I am not using the JerseyServletContainer and am instead doing this. It
seems to work but are there any red flags anyone can think of with this
approach?

public class AppInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup( ServletContext servletCtx ) throws
ServletException {
        WebApplicationContext springCtx = createSpringContext();
        servletCtx.addListener( new ContextLoaderListener( springCtx ) );
        addJerseyServlet( servletCtx, springCtx );
    }

    private void addJerseyServlet( ServletContext servletCtx,
ApplicationContext springCtx ) {
        Servlet jerseyServlet = new ServletContainer( new JerseyRestConfig(
springCtx ) );
        ServletRegistration.Dynamic dispatcher = servletCtx.addServlet(
"RestAPI", jerseyServlet );
        dispatcher.setLoadOnStartup( 2 );
        dispatcher.addMapping( "/rest/*" );
    }

    private WebApplicationContext createSpringContext() {
        AnnotationConfigWebApplicationContext context = new
AnnotationConfigWebApplicationContext();
        context.register( MySpringConfiguration.class );
        context.refresh();
        return context;
    }
}