Integrating Jersey 2 and Spring with Java Based Configuration

后端 未结 4 632
日久生厌
日久生厌 2020-12-30 12:18

I am using Jersey 2.10 and jersey-spring3 and Spring 4. I want to achieve DI(basically services) in jersey resources as well as in other places and want to create Spring Bea

4条回答
  •  天命终不由人
    2020-12-30 12:48

    Here is something that I found starting from various tutorials. Combined with other answers you should have a complete example.

    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRegistration;
    
    import com.sun.jersey.spi.spring.container.servlet.SpringServlet;
    import org.springframework.web.WebApplicationInitializer;
    import org.springframework.web.context.WebApplicationContext;
    import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
    
    public class WebInitializer implements WebApplicationInitializer {
        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
            ctx.register(AppConfig.class);
            ctx.setServletContext(servletContext);
            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ctx);
            ServletRegistration.Dynamic servlet = servletContext.addServlet("jersey-serlvet", new SpringServlet());
            servlet.addMapping("/");
            servlet.setLoadOnStartup(1);
        }
    }
    

提交回复
热议问题