How to inject dependencies into resources with Jersey?
I'm having the following code:
@Path("stores")
class StoreResources {
private ServerConfig config;
@GET
public String getAll() {
//do some stuff with ServerConfig
}
}
And I need the ServerConfig
object to be injected into this class from outside 开发者_开发知识库and use it inside the getAll()
method.
What are the possible ways to achieve it? Should I use a DI framework like Guice or Spring?
This is a good blog about Spring injection under Jersey http://javaswamy.blogspot.com/2010/01/making-jersey-work-with-spring.html
The upshot is you use annotations to flag fields that are to be injected, an example resource being
package com.km.services;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.sun.jersey.spi.inject.Inject;
import com.km.spring.SimpleBean;
@Path("/hello")
@Component
@Scope("request")
public class HelloResource {
@Inject private SimpleBean simpleBean;
@GET
@Produces("text/plain")
public String getMessage() {
return simpleBean.sayHello();
}
}
For my purposes the configuration was excessively difficult so I used a static spring resolver factory to resolve the bean. eg.
private SimpleBean simpleBean = SpringBeanFactory.getBean("mySimpleBean");
You don't need Spring or Guice to inject a ServletConfig. Jersey does through its own injection mechanism. Refer to the simple-servlet example that comes with Jersey samples distribution. Here is the sample code that injects a HttpServletRequest and a ServletConfig onto a resource:
@Path("/resource1")
public class ResourceBean1 {
@Context
HttpServletRequest servletRequest;
@Context
ServletConfig servletConfig;
@GET
@Produces("text/plain")
public String describe() {
return "Hello World from resource 1 in servlet: '" +
servletConfig.getServletName() +
"', path: '" +
servletRequest.getServletPath() +
"'";
}
}
When deploying an JAX-RS application using Servlet then ServletConfig, ServletContext, HttpServletRequest and HttpServletResponse are available for injection using @Context.
精彩评论