优秀的编程知识分享平台

网站首页 > 技术文章 正文

[Java 速成] @Service,@Repository 和 @Component 的区别 (day 8)

nanyue 2025-03-13 18:35:00 技术文章 30 ℃

对于数据库的操作,通常会涉及到业务,封装成服务,过程中可能需要用到 @Service@Repository@Controller @Component 这些注解(annotation),所以在开始整合数据库之前,我们先来认识一下这些 annotation

其它基础的注解,我们在《Java 速成 - 第一个 Java Web 项目》一文中已有介绍,有需要可以参看。


代码定义

先来看一下这些 annotation 定义的源代码:

@Component
public @interface Service {
    @AliasFor(
        annotation = Component.class
    )
    String value() default "";
}

@Component
public @interface Repository {
    @AliasFor(
        annotation = Component.class
    )
    String value() default "";
}

@Component
public @interface Controller {
    @AliasFor(
        annotation = Component.class
    )
    String value() default "";
}

可见 @Service@Repository@Controller 都是专门化的特殊的 @Component

区别与联系

@Component is a generic stereotype for any Spring-managed component or bean. 标识该类为组件,由 Spring 托管,而 @Repository, @Service, @Controller 是特殊功能的 @Component。

@Repository is a stereotype for the persistence layer(Data Access Layer). 标识该类提供了对对象进行存储、检索、更新、删除和搜索操作的机制。

@Service is a stereotype for the service layer. 标识这个类是一个服务提供者,Spring上下文将自动检测这些类。

@Controller is a stereotype for the presentation layer (spring-MVC). 标识该类是一个 controller 类,用于处理 web 请求。

那么它们是否可以互换使用呢?答案是有些存在这种可能但不推荐。比如把 @Controller 替换成 @Component,那原本起作用的 @RequestMapping 将失去作用。因为 DispatcherServlet 只会找 @Controller 注解所在的类的 @RequestMapping

小结

综上,@Service@Repository@Controller 是专门化的 @Component;它们的主要区别在于它们的目的:

@ControllerSpring MVC 中用于定义控制器,它首先是 Spring Bean,然后才是 Controller。 类似地,@Service 用于在 Service 层中保存业务逻辑的类,@Repository 用于数据访问层。

Tags:

最近发表
标签列表