@Controller vs. @RestController Annotation in Spring (original) (raw)

Last Updated : 3 Sep, 2025

Spring Framework provides two commonly used annotations for handling web requests: @Controller and @RestController. They may look similar, but they are designed for different purposes:

@Controller Annotation

**Example: Using @Controller in a Spring MVC Application

Java `

@Controller public class HomeController {

@GetMapping("/home")
public String homePage(Model model) {
    model.addAttribute("message", "Welcome to Spring MVC!");
    
    // Returns a view (home.html or home.jsp)
    return "home"; 
}

}

`

**Explanation:

@RestController Annotation

**Example: Using @RestController in a REST API

Java `

@RestController public class ProductController {

@GetMapping("/product")
public Product getProduct() {
    return new Product(1, "Laptop", 80000);
}

}

`

**Explanation:

@Controller vs @RestController

The table below demonstrates the differences between @Controller and @RestController annotations in Spring.

Feature @Controller @RestController
Definition This annotation is used to mark classes as Spring MVC controllers. This is a specialized controller used for RESTful web services.
Inheritance Extends @Component annotation. Extends @Controller annotation.
View Support Returns a view in Spring Web MVC. Cannot return a view.
Response Handling Requires @ResponseBody for sending responses as JSON or XML. Assumes @ResponseBody by default, eliminating the need for explicit annotations.
Request Handling Used for traditional MVC applications where views (JSP, Thymeleaf) are returned. Used for REST APIs where JSON or XML responses are sent directly to the client.
Spring Version Introduced in Spring 2.5. Introduced in Spring 4.0.

When to Use Which

**Use @Controller when:

**Use @RestController when: