Junior — Middle
What are the main differences between @RestController and @Controller annotations in Spring?
sobes.tech AI
Answer from AI
The @Controller annotation is used to define a controller in Spring MVC, which typically returns the name of a view for rendering an HTML page. Meanwhile, @RestController is a specialized annotation that combines @Controller and @ResponseBody. This means that methods in a class with @RestController by default return data (such as JSON or XML), rather than a view name.
Example:
@RestController
public class MyRestController {
@GetMapping("/data")
public MyData getData() {
return new MyData("value"); // Returns JSON
}
}
@Controller
public class MyController {
@GetMapping("/page")
public String getPage() {
return "pageView"; // Returns the view name for rendering
}
}
Thus, @RestController is convenient for creating REST APIs, while @Controller is used for web applications with server-side rendering.