Spring-boot读书笔记一@Controller Annotation
@Controller is a Spring Framework annotation that marks a class as a web controller component.
Purpose
- Web Layer Component: Identifies classes that handle HTTP requests in Spring MVC applications
- Stereotype Annotation: Specialization of @Component for presentation layer
Key Features
- Automatic Detection: Classes annotated with @Controller are automatically detected during component scanning
- Bean Registration: Automatically registered as Spring beans in the application context
- Request Handling: Works with @RequestMapping and related annotations to handle web requests
Basic Usage
@Controller
public class HomeController {
@RequestMapping("/home")
public String home() {
return "home"; // Returns view name
}
}
Return Types
Controllers can return:
- String: View name for template resolution
- ModelAndView: View name with model data
- ResponseEntity: Full HTTP response control
- @ResponseBody: Direct response body content
Related Annotations
- @RestController: Combines @Controller + @ResponseBody
- @RequestMapping: Maps HTTP requests to handler methods
- @GetMapping/@PostMapping: HTTP method-specific mappings
Difference from @RestController
- @Controller: Returns view names (for template rendering)
- @RestController: Returns data directly as HTTP response body
Component Scanning
Requires @ComponentScan or @SpringBootApplication to be detected:
@ComponentScan(basePackages = "com.example.controllers")
Controllers handle the presentation layer logic and coordinate between the service layer and view templates.

浙公网安备 33010602011771号