gpt4 book ai didi

java - @Repository 注解的真正目的

转载 作者:行者123 更新时间:2023-11-30 05:36:30 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com