Jānis Ošs’ Post

🚀 @RestController vs @Controller — Do You Know the Real Difference? Most Spring Boot developers reach for @RestController without thinking twice. But knowing why it exists separates good engineers from great ones. @Controller is the classic Spring MVC annotation — it marks a class as a web controller that returns view names (like Thymeleaf templates). To return JSON from a @Controller method, you must explicitly add @ResponseBody. @RestController is simply a convenience annotation that combines @Controller + @ResponseBody. Every method automatically serializes the return value to JSON/XML via Jackson — no extra annotation needed. // Classic MVC — returns a Thymeleaf view @Controller public class PageController { @GetMapping("/home") public String home(Model model) { model.addAttribute("user", "Janis"); return "home"; // resolves to home.html } } // REST API — returns JSON automatically @RestController @RequestMapping("/api/users") public class UserController { @GetMapping("/{id}") public User getUser(@PathVariable Long id) { return userService.findById(id); // auto-serialized to JSON } } The rule is simple: → Building a REST API? Always use @RestController. → Building server-side rendered views (SSR)? Use @Controller. In modern microservice architectures, @RestController dominates — because APIs communicate via JSON, not HTML pages. #Java #SpringBoot #BackendDevelopment #REST #WebDevelopment #SoftwareEngineering

To view or add a comment, sign in

Explore content categories