Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 540
Dunith Dhanushka Avatar asked Nov 08 '10 10:11

Dunith Dhanushka


1 Answers

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");
like image 65
Eldorado Avatar answered Sep 28 '22 00:09

Eldorado