How to use @Controller and @RestController annotations in Spring Framework

Tech Insights

Both @controller and @RestController annotations indicate that the annotated class is a “Controller” in the MVC. @Controller has been part of the Spring framework for a very long time. It is typically used in combination with @RequestMapping and @GetMapping annotations on request handler methods in a controller class. Also, to make it a RESTful web service, you need to use the @ResponseBody annotation with the handler methods. Spring 4.0 introduced a simplified annotation – @RestController to make the development of RESTful web services easier. @RestController is nothing but a convenience annotation that is itself annotated with @Controller and @ResponseBody. Which means, you don’t need to explicitly use the @ResponseBody annotation, for the method or API to return the data in JSON or XML format. Just check the following code examples to understand the difference quickly:

1) Usage of @Controller annotation:

@Controller
public class Learn {
	@GetMapping(path="/try")
	public @ResponseBody String tryOne() {
		// ...
		return "Ok";
	}
}

2) Usage of @RestController annotation:

@RestController
public class Learn {
	@GetMapping(path="/try")
	public String tryOne() {
		// ...
		return "Ok";
	}
}

Both the above code snippets will produce the same result. In snippet 1, we used the classic @Controller and made the tryOne() method RESTful by using @ResponseBody annotation. In snippet 2, we used the @RestController which made the tryOne() method RESTful by default.

Related read: Spring Boot vs Spring MVC