How to add dependencies to resources using jersey?

I have the following code:

@Path("stores") class StoreResources { private ServerConfig config; @GET public String getAll() { //do some stuff with ServerConfig } } 

And I need a ServerConfig object that needs to be inserted into this class from the outside and used inside the getAll() method.

What are the possible ways to achieve it? Should I use DI frameworks like Guice or Spring?

+7
rest dependency-injection jersey jax-rs
source share
2 answers

This is a good blog about Spring Injection under Jersey http://javaswamy.blogspot.com/2010/01/making-jersey-work-with-spring.html

As a result, you use annotations for the flag of the fields that should be entered, example resource

 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 overly complex, so I used the static spring factory converter to resolve the bean. eg.

 private SimpleBean simpleBean = SpringBeanFactory.getBean("mySimpleBean"); 
+5
source share

You do not need Spring or Guice to enter ServletConfig. Jersey makes through its own injection mechanism. See the simple servlet example that comes with the Jersey sample distribution. Here is an example of code that injects HttpServletRequest and ServletConfig to 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 a JAX-RS application using the ServCertFig, ServletContext, HttpServletRequest and HttpServletResponse servlets are available for injection using @Context.

+2
source share

All Articles