RESTful using Spring Framework

I don’t need to say that RESTful web services are very popular this days. So, you need it, for sure, but what to choose? I’ve tried different Java frameworks for REST, most times it was Jersey and Spring MVC, and think that for most cases Spring is the best option for building RESTful applications using Java.

If you already have a Spring app, then you don’t need to make complex configuration to start implementing RESTful API with Spring. Just configure view resolver for JSON, and use standard annotations like:

//I'm using Groovy at this example, but believe you've got the idea
@Constoller
@RequestMapping('/api/user')
class UserApi {
  @RequestMapping(value = '/{id}', method = RequestMethod.GET)
  User get(@PathVariable long id) {
     //... load user, etc
  }

  @RequestMapping(value = '/{id}', method = RequestMethod.POST)
  User update(@PathVariable long id, @RequestModel User updated) {
     //... load user, update values, etc
  }
}

Of course, you could easily switch from JSON to XML, or use along with, or ProtoBuf, or anything else. W/o serious code modification. Much easier than in Jersey.

Usually your application have other things, not only RESTful API. Standard HTML pages, file downloading/uploading. Or complicated data processing for API requests, serious background processing, access to database, complicated authentication and authorization, integration with external services, etc. Spring Framework is very good on all this things. And also, what I like, there are always at least two ways: ‘quick-and-dirty’ and a normal one :)

Actually I’m a big fan of Grails web framework, really like it, I’m author of several plugins for Grails, I believe it’s the best framework for building traditional web applications. But when I see that app is mostly RESTful, and most modern apps are, (very often just “Single Page App“) – I always suggest to use Spring MVC (+ Groovy, but it’s another story).

Some links: