以下是 Spring Boot 常用注解及其功能详解,分为几大类(核心注解、依赖注入、Web开发、配置相关、数据访问、安全等),适合日常开发参考。
🧱 一、核心注解
注解 | 功能 |
---|
@SpringBootApplication | 是 @Configuration 、@EnableAutoConfiguration 、@ComponentScan 的组合注解,是 Spring Boot 的入口 |
@ComponentScan | 自动扫描并注册 @Component 、@Service 、@Repository 、@Controller 标注的类到 Spring 容器中 |
@EnableAutoConfiguration | 启用 Spring Boot 的自动配置机制,自动根据依赖自动配置 Bean |
@Configuration | 表示当前类是一个配置类,等同于传统的 applicationContext.xml |
💉 二、依赖注入相关注解
注解 | 功能 |
---|
@Component | 标注一个普通组件类 |
@Service | 标注业务逻辑层组件 |
@Repository | 标注 DAO 层组件,并支持 Spring 的异常转换 |
@Controller | 标注控制器组件(配合 MVC) |
@RestController | 是 @Controller + @ResponseBody ,返回 JSON 数据用 |
@Autowired | 自动注入 Bean(按类型注入) |
@Qualifier | 配合 @Autowired 使用,按名称注入 Bean |
@Resource | JSR-250 标准注解,默认按名称注入 |
@Value | 注入配置文件中的值,例如 @Value("${server.port}") |
@PostConstruct | 方法在 bean 初始化完成后执行(初始化方法) |
@PreDestroy | 方法在 bean 销毁前执行(销毁方法) |
🌐 三、Web 相关注解(Spring MVC)
注解 | 功能 |
---|
@RequestMapping | 通用的请求映射,可以用于类或方法上 |
@GetMapping 、@PostMapping 、@PutMapping 、@DeleteMapping | 更简洁的请求方式映射 |
@PathVariable | 获取 URL 路径中的变量 |
@RequestParam | 获取请求参数,如 ?id=1 |
@RequestBody | 将请求体 JSON 转换为 Java 对象 |
@ResponseBody | 将返回值转为 JSON 响应(用在 @Controller 方法上) |
@CrossOrigin | 处理跨域请求 |
@ExceptionHandler | 处理控制器中的异常 |
@ControllerAdvice | 全局异常处理、数据绑定、全局数据等 |
@ModelAttribute | 绑定请求参数到模型对象上,或暴露数据到前端页面 |
🛠 四、配置与属性绑定
注解 | 功能 |
---|
@ConfigurationProperties | 将配置文件中的值绑定到 Bean 上,适合批量注入 |
@PropertySource | 指定额外的 properties 配置文件 |
@EnableConfigurationProperties | 开启 @ConfigurationProperties 支持 |
@Profile | 指定该类或 Bean 仅在某个环境 Profile 激活时加载(如 dev/prod) |
🗃 五、数据访问相关(Spring Data / JPA)
注解 | 功能 |
---|
@Entity | 标注 JPA 实体类,对应数据库表 |
@Table | 指定实体类映射的表名 |
@Id | 指定主键字段 |
@GeneratedValue | 设置主键生成策略 |
@Repository | 持久层组件,支持异常转换 |
@Transactional | 表示方法或类为事务处理方法 |
@Modifying | 用于执行更新、删除操作的自定义 JPQL 语句 |
🔒 六、安全相关(Spring Security)
注解 | 功能 |
---|
@EnableWebSecurity | 启用 Web 安全配置 |
@Secured | 基于角色的访问控制 |
@PreAuthorize / @PostAuthorize | 方法前/后进行权限校验 |
@RolesAllowed | 指定允许访问的角色(JSR-250) |
🧪 七、测试相关
注解 | 功能 |
---|
@SpringBootTest | 启动整个 SpringBoot 容器进行集成测试 |
@WebMvcTest | 只测试 Web 层(Controller) |
@DataJpaTest | 测试 JPA 相关功能 |
@MockBean | 向 Spring 容器中添加一个模拟 Bean |
@BeforeEach / @AfterEach | 测试前/后运行 |
@Test | 标注测试方法(JUnit) |
🧠 小结
核心:@SpringBootApplication = @ComponentScan + @EnableAutoConfiguration + @Configuration
依赖注入:@Autowired、@Component、@Service、@Repository
Web控制:@RestController、@RequestMapping、@GetMapping、@RequestParam、@PathVariable
配置绑定:@ConfigurationProperties、@Value
数据访问:@Entity、@Id、@Repository、@Transactional
安全控制:@Secured、@PreAuthorize
测试:@SpringBootTest、@MockBean