Spring @RestController example

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:

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.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.