Wednesday, 17 October 2012

Building a REST Java web service API using the Spring framework

Building a REST-ful Java web service API has never been more restful than now, using version 3+ of the Spring framework.

 First some annotated Java code:

public class SampleController {

     private SampleService service;

     @RequestMapping(value = "/samples/{reference}", method = {RequestMethod.GET})
     public Sample getSampleByReference(@PathVariable String reference) {
          return service.getSampleByReference(reference);

 Then some Spring config:

    <context:component-scan base-package="com.blah.sample" /> 
        <aop:aspectj-autoproxy /> 

Then some web.xml config in your web application: 

        <servlet-class>org.springframework.web.servlet.DispatcherServlet </servlet-class>

And that's about it, folks.   Spring will automagically handle JSON and XML accept reponses depending on what's in your classpath.

A fully working sample can be found here. And of course you can then generate REST documentation using RESTdoclet.  :)  Build a Java web service has never been easier in my opinion.