@Controller vs @RestController

@Controller: This annotation designates the bean class as the controller in the presentation layer (Spring MVC Controller).

@RestController was introduced in Spring 4.0 to provide better support for developing RESTful WebService in Spring Framework.

@RestController – is the combination of @Controller and @ResponseBody. It eliminates the need to annotate every request handling method of the controller class with the @ResponseBody annotation.

Using @Controller

@Controller
class StudentController {
@GetMapping(“/students”)
@ResponseBody List<Student> getAllStudents() {
return studentDAO.getAllStudents();
}
Using @RestController
@RestController
class StudentController {
@GetMapping(“/students”)
List<Student> getAllStudents() {
return studentDAO.getAllStudents();
}
}

Every request handling method of the controller class annotated with @RestController automatically serializes return objects into HttpResponse.

Leave a Reply

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