四个Spring注解:普通人、专家、管家、接待员
一句话区别
@Component:普通人,啥都能干
@Service:业务专家,专门处理业务逻辑
@Repository:数据管家,专门管理数据库
@Controller:前台接待,专门接待HTTP请求
详细对比表
| 注解 |
相当于 |
主要用途 |
特殊能力 |
类比 |
@Component |
普通员工 |
通用Bean声明 |
无 |
公司的普通职员 |
@Service |
业务专家 |
业务逻辑层 |
无技术功能,但语义清晰 |
销售部经理 |
@Repository |
数据管家 |
数据访问层 |
自动异常转换 |
仓库管理员 |
@Controller |
前台接待 |
Web控制器 |
处理HTTP请求 |
前台接待员 |
具体区别详解
1. @Component - 万金油
1 2 3 4
| @Component public class UtilityClass { }
|
特点: 最基础,其他三个都继承自它
2. @Service - 业务专家
1 2 3 4 5 6 7 8 9
| @Service public class UserService { public User register(String phone, String password) { } }
|
特点: 和@Component功能一样,但语义更清晰,一看就知道是业务层
3. @Repository - 数据管家
1 2 3 4 5 6 7
| @Repository public class UserRepository { }
|
特殊能力:
1 2 3 4 5 6 7
| try { } catch (SQLException e) { }
|
4. @Controller - 前台接待
1 2 3 4 5 6 7 8 9
| @Controller public class UserController { @GetMapping("/user/{id}") public String getUser(@PathVariable Long id) { return "userPage"; } }
|
升级版: @RestController = @Controller + @ResponseBody
1 2 3 4 5 6 7 8
| @RestController public class UserApiController { @GetMapping("/api/user/{id}") public UserDTO getUser(@PathVariable Long id) { return userService.getUser(id); } }
|
继承关系
1 2 3 4
| @Component (爷爷) ├── @Service (业务儿子) ├── @Repository (数据儿子) └── @Controller (前台儿子)
|
如何选择?
根据代码位置选择:
1 2 3 4 5 6 7
| 项目结构: ├── controller/ ← 用 @Controller / @RestController │ └── UserController.java ├── service/ ← 用 @Service │ └── UserService.java └── repository/ ← 用 @Repository └── UserRepository.java
|
例外情况:
- 工具类:用
@Component
- 第三方集成:用
@Component
- 配置类:用
@Configuration
一句话总结
想让代码分工明确,就请专业的(@Service/@Repository/@Controller);不确定的,请个万金油(@Component)也行!