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
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");
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.