@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 {
}

Popular posts from this blog

Spring boot video streaming example-HTML5

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

DataTable-Pagination example with Spring boot, jQuery and ajax

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Node JS mini projects with source code - free download

Spring boot web project free download:User Registration System

Java - Blowfish Encryption and decryption Example