@Service 是 Spring Boot 中标识业务层组件的注解,声明类为业务逻辑Bean并支持依赖注入;相比@Component,它语义更明确、利于事务管理、AOP增强与监控。

@Service 是 Spring Boot 中专门用于标注业务层(Service Layer)组件的构造型注解。它本身不执行逻辑,而是向 Spring 容器“声明”:这个类属于业务逻辑层,需要被自动管理、实例化,并支持被其他组件(如 Controller 或其他 Service)通过依赖注入使用。
为什么用 @Service 而不是 @Component
虽然 @Component 也能让类成为 Spring Bean,但 @Service 具有明确的语义——它告诉开发者和框架:“这是一个处理核心业务逻辑的类”,比如用户注册、订单创建、库存校验等。这种分层标识带来三方面好处:
- 代码可读性更强,团队能快速识别职责归属
- Spring 会为 @Repository 自动转换数据库异常,而 @Service 是事务管理(@Transactional)的常用作用域
- 在大型项目中便于扫描、切面(AOP)增强或统一监控(例如只对 @Service 方法做日志或性能埋点)
基本写法与常见搭配
通常配合接口+实现类结构使用,推荐面向接口编程:
Java项目代码review工具。分析Git变更+完整调用链路上下文,推断业务需求,进行多维度评分和分类汇总,生成完整PRD文档。包含细粒度Java代码审查清单(Null安全、异常处理、Streams、并发、equals/hashCode、资源管理、API设计、性能、MyBatis/ORM、事务边界、SQL/DD...
- 定义业务接口(可选,但利于解耦和测试):// UserService.java
public interface UserService {<br> User getById(Long id);<br> void create(User user);<br>} - 实现类加 @Service 注解:// UserServiceImpl.java
@Service<br>public class UserServiceImpl implements UserService {<br> @Autowired<br> private UserMapper userMapper; // 或 UserRepository<br><br> @Override<br> public User getById(Long id) {<br> return userMapper.selectById(id);<br> }<br><br> @Override<br> public void create(User user) {<br> userMapper.insert(user);<br> }<br>}
注入到其他层的方式
标注了 @Service 的类,会在 Spring 启动时被扫描并注册为 Bean。你可以在 Controller 或另一个 Service 中直接注入使用:
- 构造器注入(推荐):
@RestController<br>public class UserController {<br> private final UserService userService;<br><br> public UserController(UserService userService) {<br> this.userService = userService;<br> }<br><br> @GetMapping("/users/{id}")<br> public User get(@PathVariable Long id) {<br> return userService.getById(id);<br> }<br>} - 字段注入(简洁但不推荐用于关键依赖):
@Autowired<br>private UserService userService;
注意事项
使用 @Service 时需确保满足以下前提:
- 所在类必须在 Spring Boot 启动类的包扫描路径下(默认扫描启动类所在包及其子包)
- 不能是 final 类,也不能是抽象类(否则无法代理或实例化)
- 如果类实现了接口,Spring 默认按类型注入;若存在多个实现,需配合 @Qualifier 指定 Bean 名称
- 方法上添加 @Transactional 可开启事务,但仅对 public 方法生效,且调用需经过 Spring 代理(避免同类内方法直接调用)

















