Difference Between @RestController and @Controller in Spring
Spring Framework provides two important annotations for defining controllers: @Controller
and @RestController
. Although they may seem similar, they serve different purposes in web application development.
🔍 Key Differences
Feature | @Controller | @RestController |
---|---|---|
Purpose | Used in traditional MVC applications to return views (HTML/JSP). | Used in REST APIs to return JSON/XML responses directly. |
Return Type | Returns logical view names, resolved by ViewResolver. | Returns response body directly (usually JSON). |
Annotation Behavior | Requires @ResponseBody on each method to return JSON/XML. |
Automatically adds @ResponseBody to all methods. |
Common Usage | Web UI / JSP / Thymeleaf-based applications. | RESTful web services. |
📘 Example Using @Controller
@Controller public class WebController { @GetMapping("/home") public String homePage(Model model) { model.addAttribute("title", "Welcome Page"); return "home"; // resolves to home.html or home.jsp } @GetMapping("/api/message") @ResponseBody public String message() { return "Hello from @Controller with @ResponseBody"; } }
📘 Example Using @RestController
@RestController @RequestMapping("/api") public class ApiController { @GetMapping("/hello") public String hello() { return "Hello from @RestController"; } @GetMapping("/user") public User getUser() { return new User(1L, "John", "john@example.com"); } }
🧠 When to Use What?
- Use
@Controller
when building web applications with HTML views. - Use
@RestController
when developing APIs that return data as JSON/XML.
🎯 Tip
@RestController
is simply a shorthand for @Controller + @ResponseBody
.
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Controller @ResponseBody public @interface RestController { }
✅ Conclusion
Understanding the distinction between @Controller
and @RestController
is crucial for developing scalable Spring applications. Choose wisely based on your project needs — view-based or data-based.
🔗 Related Posts
🏷️ Spring REST Annotations
Understand key annotations like @GetMapping, @PostMapping, @RequestBody, and more.
🚨 Global Exception Handling
Handle errors cleanly across all controllers using @ControllerAdvice and @ExceptionHandler.
🛠️ CRUD API with Oracle DB
Build a full CRUD API using Spring Boot, Oracle, and RESTful controllers.
💡 Java Exception Best Practices
Learn clean exception management principles in core Java.