java - @Repository 注解的真正目的

标签 java spring spring-boot spring-mvc

Spring 我们有 @Componenet , @Repository注释。我研究了一些东西,发现 @Component 之间存在以下差异和另一个。

@Repository注释是任何满足存储库角色或构造型(也称为数据访问对象或 DAO)的类的标记。

  1. 我的困惑是我们是否替换 @Repository@Component ,我们有任何错误吗(我怀疑)。如果是这样,是否有可能通过使用@Component来实现存储库的构造型/功能+一些手动配置(我们称之为样板代码)。我问这个只是为了更好地理解这个概念。

  2. 博客中发布的第二个主要意义是,如果我们使用基于图层的注释(如@Service),异常处理会更好。 , @Controller , @Repository 。但找不到很好的解释或例子。

最佳答案

来自Spring Framework Documentation :

Spring provides further stereotype annotations: @Component, @Service, and @Controller. @Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases (in the persistence, service, and presentation layers, respectively). Therefore, you can annotate your component classes with @Component, but, by annotating them with @Repository, @Service, or @Controller instead, your classes are more properly suited for processing by tools or associating with aspects. For example, these stereotype annotations make ideal targets for pointcuts. @Repository, @Service, and @Controller can also carry additional semantics in future releases of the Spring Framework. Thus, if you are choosing between using @Component or @Service for your service layer, @Service is clearly the better choice. Similarly, as stated earlier, @Repository is already supported as a marker for automatic exception translation in your persistence layer.

这意味着它们在那里,因此您可以使用它们来指示功能。 @Service 用于服务,@Repository 用于存储库等。我们这样做是为了更轻松地识别被修饰代码的意图。它在定义方面(如面向方面编程)时也很有帮助,因此我们可以说“所有存储库都应该有 X 切入点”,而不必拼写出包或任何内容。我们只需查找 @Repository 注释即可。

我之前对我的类进行了错误分类(使用@Component作为@Service)并且从未遇到任何问题。但这并不是说不会出现问题,特别是当 Spring 或其他一些库将它们用于 AOP 目的时。

关于java - @Repository 注解的真正目的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56499601/

相关文章:

java - Spring Boot Rest 响应返回 login.jsp

java - 在集成测试中覆盖 bean

java - 如何使用可变日期作为数组名称的 JSON - Java/Spring

spring-boot - Spring集成TCP客户端抛出 'Socket closed during message assembly'异常

spring-boot - 如何使用 Spring Kafka 测试 Kafka Streams 应用程序?

java - Springboot提交未找到 Controller

java - 除以 2 右移运算符和传统除法运算符哪个更好?

java - PDF 单元格垂直对齐与 com.lowagie.text

java - jpa 实体 bean 的默认范围是什么?它有何帮助?

java - 恢复(取消)对 SpringData 存储库实体的更改