@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

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

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

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

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

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