What is the difference between RestController and Controller annotations in Spring?
sobes.tech AI
Answer from AI
@Controller is used to define controllers that handle web requests. Methods in such a class typically return view names, which Spring MVC then renders.
@RestController is a specialized version of @Controller. It combines @Controller and @ResponseBody. This means that methods in such a class by default do not return view names, but directly return objects that are then automatically serialized into JSON or XML (depending on configuration) and sent back to the client in the HTTP response body.
Thus, the main difference is that @Controller is intended for creating web applications with traditional server-side rendering of views (MVC architecture), while @RestController is for creating RESTful web services, where responses are presented as data.
You can say that @RestController is syntactic sugar for @Controller plus @ResponseBody.
// Example of using @Controller
@Controller
@RequestMapping("/pages")
public class ViewController {
@GetMapping("/welcome")
public String showWelcomePage() {
return "welcome"; // Returns the view name (welcome.html, welcome.jsp, etc.)
}
}
// Example of using @RestController
@RestController
@RequestMapping("/api")
public class ApiController {
@GetMapping("/users/{id}")
public User getUserById(@PathVariable Long id) {
// Returns a User object, which will be automatically serialized into JSON/XML
return userService.findById(id);
}
}