@Component、@Repository & 之间有什么区别?Spring 中的 @Service 注释? [英] What's the difference between @Component, @Repository & @Service annotations in Spring?

查看:31
本文介绍了@Component、@Repository & 之间有什么区别?Spring 中的 @Service 注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以@Component, @Repository@Service 注释在 Spring 中可以互换使用,还是除了充当注释设备之外还提供任何特定功能?

Can @Component, @Repository and @Service annotations be used interchangeably in Spring or do they provide any particular functionality besides acting as a notation device?

换句话说,如果我有一个 Service 类并且我将注释从 @Service 更改为 @Component,它的行为是否仍然相同?

In other words, if I have a Service class and I change the annotation from @Service to @Component, will it still behave the same way?

或者注解是否也会影响类的行为和功能?

Or does the annotation also influence the behavior and functionality of the class?

推荐答案

来自 Spring 文档:

@Repository 注释是任何满足存储库的角色或构造型(也称为数据访问对象或 DAO).此标记的用途之一是自动翻译异常,如 异常翻译.

The @Repository annotation is a marker for any class that fulfils the role or stereotype of a repository (also known as Data Access Object or DAO). Among the uses of this marker is the automatic translation of exceptions, as described in Exception Translation.

Spring 提供了更多的构造型注解:@Component@Service、和 @Controller.@Component 是任何的通用构造型Spring 管理的组件.@Repository@Service@Controller@Component 的专门化,用于更具体的用例(在分别为持久层、服务层和表示层).因此,您可以使用 @Component 注释您的组件类,但是,通过使用 @Repository@Service@Controller 注释它们相反,您的类更适合由工具处理或与方面相关联.

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.

比如这些构造型注释为切入点制作理想的目标.@Repository@Service@Controller 还可以在未来的版本中携带额外的语义弹簧框架.因此,如果您在使用之间进行选择@Component@Service 用于您的服务层,@Service 显然是更好的选择.同样,如前所述,@Repository 已经是支持作为自动异常翻译的标记持久层.

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.

<头>
注释含义
@Component任何 Spring 管理组件的通用构造型
@Repository持久层的原型
@Service服务层的原型
@Controller表示层的原型(spring-mvc)

这篇关于@Component、@Repository &amp; 之间有什么区别?Spring 中的 @Service 注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆