Integrating Jersey 2 and Spring with Java Based Configuration

后端 未结 4 625
日久生厌
日久生厌 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

    Old Fashioned way:

    Since you have already initialized the ContextLoaderListener a simple trick is to use the WebApplicationContext to retrieve your beans at any application point:

    WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    SomeBean someBean = (SomeBean) ctx.getBean("someBean");
    

    Jersey Support:

    Or you can use the annotation based discovery, since Jersey has already support for Spring DI. You have to register your beans under your main application entry point. That entry point, in below example will be some.package.MyApplication, should be provided as an of the servlet container:

    
      SpringApplication
      org.glassfish.jersey.servlet.ServletContainer
      
        javax.ws.rs.Application
        some.package.MyApplication
      
      1
    
    

    Register you beans in your application:

    package some.package;
    
    import org.glassfish.jersey.server.ResourceConfig;
    import org.glassfish.jersey.server.spring.scope.RequestContextFilter;
    
    public class MyApplication extends ResourceConfig {
      public MyApplication () {
        register(RequestContextFilter.class);
        register(SomeBean.class);
        // ...
      }
    }
    

    Here you can take a look to a ready to run example from Jersey Git repo.

提交回复
热议问题