Improve Your Spring REST API, Part IV

Spring 4 is around the corner. Milestone releases has been available for a while, the first release candidate was released earlier today, and the final release is expected before the end of this year.

@RestController

One new feature that has been added is the @RestController annotation, which provide some syntactic sugar to your controller. Take a look at the following code snippet:

Did you notice anything different? Ok, there is the new annotation on the class, an autowired dependency, a method that returns a domain object based on a path variable, so what? Look again, did you notice that the @ResponseBody annotation was missing from the method declaration? Despite that, the server will return a Person instance serialized to JSON in the response body.

To make this possible, the @ResponseBody annotation has been promoted in Spring 4 to type level, which means it can be added to classes, interfaces and other annotations. Next, the new @RestController annotation is simply created by composing the @ResponseBody annotation with the existing @Controller annotation (copied from the source code):

Spring 4 RC1

To start using the @RestController annotation and explore other Spring 4 features today, you can add the Spring milestone repository to your list of Maven repositories:

and update your Spring dependencies to version 4.0.0.RC1, e.g.

Mattias Severson

Mattias is a senior software engineer specialized in backend architecture and development with experience of cloud based applications and scalable solutions. He is a clean code proponent who appreciates Agile methodologies and pragmatic Test Driven Development. Mattias has experience from many different environments, including everything between big international projects that last for years and solo, single day jobs. He is open-minded and curious about new technologies. Mattias believes in continuous improvement on a personal level as well as in the projects that he is working on. Additionally, Mattias is a frequent speaker at user groups, companies and conferences.

Leave a Reply

Close Menu