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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With