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

标签 java spring spring-mvc annotations

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

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

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

最佳答案

来自 Spring Documentation :

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 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.

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

关于java - Spring中的@Component、@Repository和@Service注解有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6827752/

相关文章:

java - 无法理解我的 Spring DTO 的工作原理

java - Spring 安全出版

java - 在 spring mvc Controller 中获取不支持的媒体类型

java - 关于 ActionPerformed 和 ActionEvent

java - 将 java 方法引用分配给接口(interface)

java - Android:当 sleep 或等待不起作用时,如何在方法中设置时间间隙

java - 如何使用 spring mvc 3.0 注册处理程序拦截器?

java - libsodium + Windows 10 x64 + Eclipse

java - 无法通过反射 getter 和查询来获取字段值以在纯 Hibernate 中对多个列求和

spring-mvc - 如何 JUnit 测试 @PreAuthorize 注释及其由 spring MVC Controller 指定的 spring EL?