In this post, we are going to see another important annotation called @RestController. It is generally used while working with Spring restful Web services implementation.
Spring MVC tutorial:
- Spring MVC hello world example
- Spring MVC Hibernate MySQL example
- Spring MVC interceptor example
- Spring MVC angularjs example
- Spring MVC @RequestMapping example
- Spring Component,Service, Repository and Controller example
- Spring MVC @ModelAttribute annotation example
- Spring MVC @RestController annotation example
- Spring MultiActionController Example
- Spring MVC ModelMapSpring MVC file upload example
- Spring restful web service example
- Spring restful web service json example
- Spring Restful web services CRUD example
- Spring security hello world example
- Spring security custom login form example
If we need to directly get resource from controller, we need to return @ResponseBody as per Spring 3 but with Spring 4, we can use @RestController for that.
In spring 4.0, we can use @RestController which is combination of @Controller + @ResponseBody.
@RestController = @Controller + @ResponseBody
So
@Controller
public class CountryController {
@RequestMapping(value = "/countries", method = RequestMethod.GET,headers="Accept=application/json")
public @ResponseBody List getCountries()
{
List listOfCountries = new ArrayList();
listOfCountries=createCountryList();
return listOfCountries;
}
Is same as
@RestController
public class CountryController {
@RequestMapping(value = "/countries", method = RequestMethod.GET,headers="Accept=application/json")
public List getCountries()
{
List listOfCountries = new ArrayList();
listOfCountries=createCountryList();
return listOfCountries;
}
Instead of annotating each method return type as @ResponseBody, we can directly annotate a class with @RestController. You can see Spring rest Json example to get complete working example on @RestController.