@Controller Vs @RestController - Spring
Hello everyone, I hope you all are doing well.Well, today we will discuss the difference between @Controller and @RestController
@Controller
The @Controller annotation has been part of the framework for a very long time.@Controller annotation designates that the annotated class is a controller. It is a specialization of @Controller and is autodetected through classpath scanning. It is typically utilized in amalgamation with annotated handler methods predicated on the @RequestMapping annotation.
For example,
@Controller
@RequestMapping("users")
public class HomeController {
@GetMapping(produces = "application/json")
public @ResponseBody User getAllUsers() {
return findAllUsers();
}
}
The request handling method is annotated with @ResponseBody. This annotation enables automatic serialization of the return object into the HttpResponse.
@RestController
The @RestController annotation was introduced in Spring 4.0 to simplify the engenderment of RESTful web services. It's an convenience annotation that combines @Controller and @ResponseBody
For example,
@RestController
@RequestMapping("users")
public class HomeController {
@GetMapping(produces = "application/json")
public Book getAllUsers() {
return findAllUsers();
}
}
The controller is annotated with the @RestController annotation, consequently the @ResponseBody isn't required. Every request handling method of the controller class automatically serializes return objects into HttpResponse.
Conclusion
- @Controller is utilized to mark classes as Spring MVC Controller.
- @RestController is an convenience annotation that does nothing more than integrating the @Controller and @ResponseBody annotations
So the following two controller definitions should do the same
@Controller
@ResponseBody
public class HomeController {
}
@RestController
public class HomeController {
}