Spring @RestController vs @Controller: Key Differences

🚀 Java Backend Interview Series – Question #78 Q78. What is the difference between @RestController and @Controller in Spring? If you work with Spring Boot, you’ve definitely used: 👉 @Controller 👉 @RestController But in interviews, a very common question is: 👉 “When should you use @RestController vs @Controller?” Let’s break it down clearly 👇 🔹 1️⃣ @Controller @Controller is used in Spring MVC for building web applications (UI-based). Example: @Controller public class HomeController { @GetMapping("/home") public String home() { return "home"; // returns view name } } 📌 Behavior: ✔ Returns view name (HTML/JSP) ✔ Used with Thymeleaf / JSP / UI rendering 🔹 2️⃣ @RestController @RestController is used for building REST APIs. It is a combination of: @Controller + @ResponseBody Example: @RestController public class UserController { @GetMapping("/users") public List<String> getUsers() { return List.of("A", "B", "C"); } } 📌 Behavior: ✔ Returns JSON/XML data ✔ No view rendering 🔹 3️⃣ Key Differences Feature@Controller@RestControllerPurposeWeb MVC (UI)REST APIsReturn TypeView (HTML/JSP)JSON/XML@ResponseBodyRequiredIncluded by defaultUse CaseFrontend renderingBackend APIs🔹 4️⃣ When Should You Use Each? ✔ Use @Controller when: Building web pages Returning views/templates ✔ Use @RestController when: Building REST APIs Returning data (JSON/XML) 🔹 5️⃣ Real-World Backend Insight In modern applications: ✔ Most backend services use @RestController ✔ @Controller is mainly used in traditional MVC apps 👉 In microservices architecture, @RestController is dominant 🔹 6️⃣ Important Detail Even in @Controller, you can return JSON: @ResponseBody public String data() { return "Hello"; } But @RestController makes it default and cleaner. 🎯 Interview Tip A tricky question: 👉 “Can we use @Controller for REST APIs?” Answer: ✔ Yes, by adding @ResponseBody ❗ But @RestController is preferred 💬 Follow-up Interview Question What is the difference between @RequestBody and @ResponseBody? #Java #SpringBoot #RestController #Controller #RESTAPI #JavaDeveloper #BackendDevelopment #CodingInterview #TechInterview #SoftwareEngineering #Microservices #Programming #CleanCode #SpringFramework #APIDesign

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories