Spring Boot 常用注解
启动、控制器、注入、配置、事务、校验
启动与分层
@SpringBootApplication // 启动类
@Service @Repository @Component // 交给 Spring 管理
@Configuration @Bean // 配置类与 Bean 定义
Web
@RestController // = @Controller + @ResponseBody
@RequestMapping("/api/user")
@GetMapping("/{id}") @PostMapping @PutMapping @DeleteMapping
@PathVariable Long id // /user/1
@RequestParam(required = false, defaultValue = "1") int page
@RequestBody User user // JSON 请求体
@ModelAttribute Post post // 表单绑定
注入
// 推荐构造器注入(不用 @Autowired 字段注入)
public PostController(PostService postService) {
this.postService = postService;
}
配置
@Value("${server.port}") // 单个值
@Value("${app.admin.default-password:123456}") // 带默认值
@ConfigurationProperties(prefix = "app") // 批量绑定
事务与校验
@Transactional // 声明式事务
@Valid @NotNull @NotBlank @Size(min = 1, max = 100)