网站首页 > 技术文章 正文
对于数据库的操作,通常会涉及到业务,封装成服务,过程中可能需要用到 @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;它们的主要区别在于它们的目的:
@Controller 在 Spring MVC 中用于定义控制器,它首先是 Spring Bean,然后才是 Controller。 类似地,@Service 用于在 Service 层中保存业务逻辑的类,@Repository 用于数据访问层。
- 上一篇: 一篇深入理解分层架构的文章
- 下一篇: 清晰架构:融合 DDD、洋葱架构、整洁架构、CQRS (译)
猜你喜欢
- 2025-03-13 浅谈命令查询职责分离(CQRS)模式
- 2025-03-13 详细介绍一下Spring Boot3中如何整合JPA技术?
- 2025-03-13 SpringBoot——100种常用注解(分类版)
- 2025-03-13 京东大佬问我,每天新增100w订单数据的分库分表方案
- 2025-03-13 SpringBoot整合Spring Data JPA
- 2025-03-13 (新手勿进,全是代码)@ComponentScan、@ComponentScans详解
- 2025-03-13 清晰架构:融合 DDD、洋葱架构、整洁架构、CQRS (译)
- 2025-03-13 一篇深入理解分层架构的文章
- 2025-03-13 Spring Data JPA——多表设计、一对多、多对多、多表查询
- 2025-03-13 整理了20个经典的Spring Boot面试题
- 最近发表
- 标签列表
-
- cmd/c (57)
- c++中::是什么意思 (57)
- sqlset (59)
- ps可以打开pdf格式吗 (58)
- phprequire_once (61)
- localstorage.removeitem (74)
- routermode (59)
- vector线程安全吗 (70)
- & (66)
- java (73)
- org.redisson (64)
- log.warn (60)
- cannotinstantiatethetype (62)
- js数组插入 (83)
- resttemplateokhttp (59)
- gormwherein (64)
- linux删除一个文件夹 (65)
- mac安装java (72)
- reader.onload (61)
- outofmemoryerror是什么意思 (64)
- flask文件上传 (63)
- eacces (67)
- 查看mysql是否启动 (70)
- java是值传递还是引用传递 (58)
- 无效的列索引 (74)