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

Comments

Popular posts from this blog

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

Java, Spring Boot Mini Project - Library Management System - Download

Java - DES Encryption and Decryption example

Java - Blowfish Encryption and decryption Example

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete

ReactJS - Bootstrap - Buttons

Top 5 Java ORM tools - 2024

Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

Java - How to Count the Number of Occurrences of Substring in a String