java
技术随笔
Spring Boot 常用注解大全(启动、Web、注入、配置)
Spring Boot 大量使用注解来替代 XML 配置。下面按“启动类、Web 层、依赖注入、数据/配置”分类梳理最常用的注解。
一、启动与自动配置
@SpringBootApplication:组合注解,等价于@Configuration+@EnableAutoConfiguration+@ComponentScan。@EnableAutoConfiguration:根据 classpath 依赖自动配置 Spring 应用(如检测到 HSQLDB 就自动配置内存数据库)。@ComponentScan:扫描@Component、@Service、@Controller等并注册为 Bean;默认扫描启动类所在包及其子包。@Configuration:声明配置类,相当于 XML 配置文件,内部可用@Bean定义 Bean。
二、Web 层(Spring MVC)
@Controller:定义控制器,方法返回通常解析为视图名。@RestController:@Controller+@ResponseBody,返回直接写入 HTTP 响应体(REST 接口)。@RequestMapping:映射 URL 到方法,可指定 method/path。@GetMapping / @PostMapping / @PutMapping ...:@RequestMapping的快捷写法。@PathVariable:获取路径变量,如/user/{id}。@RequestParam:获取查询参数。@RequestBody:将请求体 JSON 反序列化为对象。@ResponseBody:返回值直接写入响应体,常用于返回 JSON。
三、依赖注入
@Autowired:按类型自动注入 Bean(可用在构造器、字段、setter 上,推荐构造器注入)。@Service / @Repository / @Component:分别标记业务层、持久层、通用组件,被扫描后注册为 Bean。
四、示例
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@RestController
@RequestMapping("/demo")
public class DemoController {
@Autowired
private DemoService demoService;
@GetMapping("/{id}")
public String get(@PathVariable Long id) {
return demoService.find(id);
}
}