✅ Spring Boot 常用注解
大约 2 分钟
✅ Spring Boot 常用注解
🌐 一、Web 层请求处理注解
| 注解 | 说明 |
|---|---|
@RestController | 组合注解:@Controller + @ResponseBody,返回 JSON |
@Controller | 返回视图名称,用于页面跳转 |
@ResponseBody | 方法返回 JSON 体 |
@RequestMapping | 通用路由映射,支持所有 HTTP 方法 |
@GetMapping / @PostMapping / @PutMapping / @DeleteMapping / @PatchMapping | 映射具体 HTTP 方法请求 |
@PathVariable | 获取 URL 路径变量 /user/{id} |
@RequestParam | 获取 query 参数 /search?name=Tom |
@RequestHeader | 获取请求头信息 |
@RequestBody | 接收 JSON 对象并绑定到 Java Bean |
@ResponseStatus | 设置响应状态码,如 201 Created |
@CrossOrigin | 启用跨域请求支持 |
@ExceptionHandler | 局部异常处理方法 |
@RestControllerAdvice | 全局异常处理类(结合 @ExceptionHandler 使用) |
🧩 二、依赖注入与 Bean 管理注解
| 注解 | 说明 |
|---|---|
@Autowired | 按类型注入 Bean |
@Qualifier | 配合 @Autowired,指定注入 Bean 名称 |
@Resource | JSR-250,默认按名称注入 |
@Inject | JSR-330,按类型注入(等价于 @Autowired) |
@Component | 通用组件注解 |
@Service | 服务层组件(语义化) |
@Repository | DAO 层组件,支持异常转换 |
@ControllerAdvice | 全局异常处理控制器 |
@Configuration | Java 配置类 |
@Bean | 定义一个 Bean 方法(常用于手动构造实例) |
@Primary | 当存在多个候选 Bean 时被优先注入 |
@Lazy | 延迟初始化 Bean |
@Scope | 设置 Bean 的作用域:singleton、prototype、request、session 等 |
🛠 三、配置与属性注入注解
| 注解 | 说明 |
|---|---|
@Value | 注入配置项值 @Value(\"${app.name}\") |
@ConfigurationProperties | 将配置文件映射到类上,支持批量注入 |
@PropertySource | 指定额外的配置文件(如非 application.properties) |
@EnableConfigurationProperties | 启用 @ConfigurationProperties 的类注入 |
@Profile | 激活某个环境配置(如 dev、test、prod) |
@PropertySources | 多个 @PropertySource 组合 |
⚙️ 四、自动配置与应用入口注解
| 注解 | 说明 |
|---|---|
@SpringBootApplication | 启动类注解(组合注解) |
@SpringBootConfiguration | Spring Boot 的配置类 |
@EnableAutoConfiguration | 开启自动配置 |
@ComponentScan | 指定组件扫描路径 |
@Import | 导入配置类或 Bean |
@ImportResource | 导入 XML 配置文件 |
🌀 五、AOP、事件监听与生命周期
| 注解 | 说明 |
|---|---|
@Aspect | AOP 切面类(配合 @Before, @After, @Around) |
@Before / @After / @Around / @AfterReturning / @AfterThrowing | AOP 切入点逻辑控制 |
@PostConstruct | Bean 初始化后执行的方法 |
@PreDestroy | Bean 销毁前执行的方法 |
@EventListener | 监听 Spring 事件(如 ApplicationReadyEvent) |
🔐 六、安全与认证相关注解(Spring Security)
| 注解 | 说明 |
|---|---|
@Secured | 指定角色访问控制(Spring Security) |
@PreAuthorize | 方法执行前鉴权 |
@PostAuthorize | 方法执行后鉴权 |
@EnableGlobalMethodSecurity | 启用方法级安全注解 |
@WithMockUser | 测试时模拟登录用户 |
🧪 七、测试相关注解
| 注解 | 说明 |
|---|---|
@SpringBootTest | 启动完整应用上下文 |
@WebMvcTest | 启动 Web 层测试 |
@DataJpaTest | 启动 JPA 层测试 |
@MockBean | 注入 mock 对象替换真实 Bean |
@TestConfiguration | 专用于测试类的配置 |
@ContextConfiguration | 加载测试上下文配置 |
