@Component、@Repository 和 @Repository 有什么区别?Spring中的@Service注释?

2022-01-13 00:00:00 annotations spring java spring-mvc

可以@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)

相关文章