@Component、@Repository和@Service注释是否可以在Spring中互换使用,或者它们除了充当符号设备之外,是否提供任何特定功能?
换句话说,如果我有一个Service类,并且我将注释从@Service更改为@Component,它的行为是否仍然相同?
或者注释是否也会影响类的行为和功能?
@Component、@Repository和@Service注释是否可以在Spring中互换使用,或者它们除了充当符号设备之外,是否提供任何特定功能?
换句话说,如果我有一个Service类,并且我将注释从@Service更改为@Component,它的行为是否仍然相同?
或者注释是否也会影响类的行为和功能?
当前回答
即使它的行为相同,但这利用了应用程序的许多软件开发原则,也很少有这样的例子:
- Single Responsibility
- Open Closed Principal
其他回答
@组件在配置类中充当@Bean注释,在spring上下文中注册Bean。它也是@Service、@Repository和@Controller注释的父级。
@服务,扩展了@Component注释,只有命名差异。
@Repository-扩展@Component注释并将所有数据库异常转换为DataAccessException。
@控制器-在MVC模式中充当控制器。分派器将扫描这些带注释的类以查找映射方法,检测@RequestMapping注释。
来自Spring文档:
@Repository注释是满足存储库的角色或原型(也称为数据访问对象或DAO)。该标记的用途之一是自动翻译异常,如异常转换中所述。Spring提供了更多的原型注释:@Component、@Service、,和@Controller@组件是任何Spring管理的组件@Repository、@Service和@Controller是@Component的专门化,用于更具体的用例(在持久性、服务和表示层)。因此,您可以使用@component注释组件类,但是,通过用@Repository、@Service或@Controller注释它们相反,您的类更适合由工具处理或与方面相关。例如,这些原型注释成为切入点的理想目标@存储库、@Service和@控制器还可以在未来版本的Spring框架。因此,如果您在使用@组件或服务层的@Service,@Service显然是更好的选择。同样,如前所述,@Repository已经支持作为自动异常转换的标记持久层。
Annotation | Meaning |
---|---|
@Component |
generic stereotype for any Spring-managed component |
@Repository |
stereotype for persistence layer |
@Service |
stereotype for service layer |
@Controller |
stereotype for presentation layer (spring-mvc) |
@组件是顶级通用注释,它使带注释的bean能够被扫描并在DI容器中可用
@Repository是专门的注释,它具有转换DAO类中所有未检查的异常的功能
@服务是专门的注释。到目前为止,它没有带来任何新特性,但它阐明了bean的意图
@控制器是专门的注释,它使bean MVC意识到,并允许使用进一步的注释,如@RequestMapping等
以下是更多详细信息
在Spring 4中,最新版本:
@Repository注释是满足存储库的角色或原型(也称为数据访问对象或DAO)。该标记的用途之一是自动翻译第20.2.2节“例外翻译”中所述的例外。Spring提供了更多的原型注释:@Component、@Service、,和@Controller@组件是任何Spring管理的组件@Repository、@Service和@Controller是@Component的专门化,用于更具体的用例例如,在持久性、服务和表示层中,分别地因此,可以使用@组件,但使用@Repository、@Service或@相反,您的类更适合通过工具处理或与方面相关。例如,这些原型注释是切入点的理想目标。它也是@Repository、@Service和@Controller可能携带Spring框架未来版本中的附加语义。因此如果您选择使用@Component或@Service服务层,@service显然是更好的选择。同样,作为如上所述,@Repository已被支持作为持久化层中的自动异常转换。
@存储库@Service和@Controller用作@Component的专用化,以便更具体地使用。在此基础上,您可以将@Service替换为@Component,但在这种情况下,您会失去专用化。
1. **@Repository** - Automatic exception translation in your persistence layer.
2. **@Service** - It indicates that the annotated class is providing a business service to other layers within the application.