SpringBoot的@Service和@Component
@Service 源码
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component // 看这里
public @interface Service {
// ...
}
@Controller 源码
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component // 看这里
public @interface Controller {
// ...
}
@Repository 源码
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented // 看这里
@Component
public @interface Repository {
// ...
}
@Service、 @Controller、@Repository
的 元注解 都应用了 @Component
,这就能看出来从核心功能上讲,@Service、 @Controller、@Repository
和 @Component
做的事情几乎完全一样:都是将一个类标识为 Spring Bean,交由 Spring 容器进行管理。但它们在语义和应用分层上有明确的区别。
- Web 层 (
@Controller
) : 接收 HTTP 请求,调用服务层。 - 服务层 (
@Service
) : 处理核心业务逻辑。 - 持久层 (
@Repository
) : 与数据库进行交互。 @Component
是 Spring 框架中最基础、最通用的构造型注解。它的作用就是告诉 Spring:“请扫描这个类,为它创建一个实例(Bean),并放到 IoC 容器里管理起来。 ”