Monday, January 18, 2010

Making Jersey work with Spring

Making Jersey work with Spring simplifies JAX-RS (Restful webservices) and make Restful services development look lot easier. This is simple tutorial of how to make Jersey work with Spring3.0 (Same can be applied to Spring 2.5)

Libraries needed:
1) Spring 3.0 distribution.
2) Jersey 1.x distribution.
3) Jersey Spring 1.0.1-SNAPSHOT

Lets Inject a simple Spring Bean using Jersey @Inject annotation.

Step 1: Update web.xml
Declare the following application context configuration for Spring:



contextConfigLocation
classpath:applicationContext.xml



Configure Spring Context Listener:


org.springframework.web.context.ContextLoaderListener



Configure Spring Request Context Listener for Spring to use request scope for Spring beans:


org.springframework.web.context.request.RequestContextListener



Now declare Jersey Spring Servlet:


jerseyspring
com.sun.jersey.spi.spring.container.servlet.SpringServlet
1


jerseyspring
/resource/*



Step 2: Create applicationContext.xml
Now create applicationContext.xml to scan JAX-RS resources in a package say com.km.services and create simple bean using Spring say com.km.spring.SimpleBean



xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">






Step 3: Define your spring bean

In this case for simplification lets create a spring which does nothing but provide a method that says hello.

package com.km.spring;

public class SimpleBean {
public String sayHello() {
return "Hello my Friend";
}
}


Step 4: Create your JAX-RS resource
Now lets create the JAX-RS to which we inject the Spring Bean that is created in Step 3.

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();
}
}



Its as simple as that. Now /resource/hello will result in printing "Hello my Friend" in your client.