springboot的注解
以下是 Spring Boot 开发中常用的注解分类及核心功能说明,结合实际应用场景整理:
---
🏗️ 一、核心配置与组件管理
1. `@SpringBootApplication`
- 作用:启动类核心注解,组合了 `@Configuration`(配置类)、`@EnableAutoConfiguration`(自动配置)、`@ComponentScan`(组件扫描)。
- 示例:
```java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
2. `@Component` & 分层注解
- `@Service`(业务层)、`@Repository`(数据访问层)、`@Controller`(MVC 控制器)、`@RestController`(RESTful 控制器,等价于 `@Controller + @ResponseBody`)。
- 区别:`@RestController` 直接返回数据(如 JSON),而 `@Controller` 返回视图(如 HTML)。
3. `@Configuration` & `@Bean`
- 作用:`@Configuration` 声明配置类,`@Bean` 在配置类中定义 Spring 管理的 Bean。
- 示例:
```java
@Configuration
public class AppConfig {
@Bean
public DataSource dataSource() {
return new DataSource();
}
}
```
---
⚙️ 二、依赖注入与装配
1. `@Autowired`
- 作用:自动按类型注入依赖(支持字段、构造函数、方法)。
- 示例:
```java
@Service
public class UserService {
@Autowired
private UserRepository repository;
}
```
2. `@Qualifier` & `@Resource`
- `@Qualifier("beanName")`:解决同类型多 Bean 的注入歧义。
- `@Resource`:按名称注入(JSR-250 规范),默认行为类似 `@Autowired`。
---
🌐 三、Web 开发与请求处理
1. `@RequestMapping` 及其衍生注解
- `@GetMapping`/`@PostMapping`:简化 HTTP 方法映射(替代 `@RequestMapping(method=...)`)。
- 参数绑定:
- `@PathVariable`:获取 URL 路径参数。
- `@RequestParam`:获取查询参数。
- `@RequestBody`:接收请求体数据(如 JSON)。
2. `@ResponseBody` & `@RestController`
- 作用:直接返回数据到 HTTP 响应体(如 JSON),`@RestController` 已隐含此功能。
---
🔧 四、配置与属性管理
1. `@ConfigurationProperties` & `@PropertySource`
- `@ConfigurationProperties(prefix="配置前缀")`:绑定配置文件属性到 Java 对象。
- `@PropertySource("classpath:config.properties")`:指定外部属性文件。
2. `@Value`
- 作用:注入单个配置属性或 SpEL 表达式。
- 示例:
```java
@Value("${server.port}")
private int port;
```
---
⚠️ 五、事务、异步与全局处理
1. `@Transactional`
- 作用:声明式事务管理,确保数据库操作的原子性。
2. `@Async` & `@EnableAsync`
- 作用:异步执行方法,需配合 `@EnableAsync` 启用。
3. `@ControllerAdvice` & `@ExceptionHandler`
- 作用:全局异常处理,统一捕获控制器抛出的异常。
---
⏱️ 六、其他实用注解
- `@Scheduled` & `@EnableScheduling`:定时任务调度。
- `@Profile`:按环境激活 Bean(如开发/生产环境)。
- `@Test` & `@SpringBootTest`:单元测试与集成测试。
---
💎 总结
以上注解覆盖了 Spring Boot 开发的核心场景,实际使用中需注意:
- 分层明确:`@Service`/`@Repository` 等注解体现分层设计。
- 依赖注入:优先使用 `@Autowired` + `@Qualifier` 解决多 Bean 冲突。
- 配置管理:复杂配置用 `@ConfigurationProperties`,简单值用 `@Value`。
更多细节可参考 [Spring Boot 官方文档](https://spring.io/projects/spring-boot) 或相关技术博客。