问题描述
为什么我们需要在服务实现中使用 @service
,并在DAO实现中使用 @repository
。当我在spring MVC中交换 @service
和 @repository
注释时,没有问题。
Why we needs to use @service
inside the service Implementation and @repository
in the DAO Implementation. There are no problem occur when I interchange the @service
and @repository
annotation in the spring MVC.
推荐答案
根据 @Repository
, @Service
, @Controller
都是同义词。它们都只是 @Component
注释的特化。因此,一般来说,它们可以用于其他一种。但是......你不应该这样做。
According to documentaion @Repository
,@Service
,@Controller
are all synonyms. They all just specializations of @Component
annotation. So, generally, they can be used one istead of other. But ... you should not do this.
第一个原因:这些注释中的任何一个都明确了应用程序中组件的角色。显示 - 此组件属于控制器,服务或数据层。
First reason: any of this annotations make clear the role of your component in the application. Shows - is this component belongs to controller, service, or data layer.
第二个原因:某些注释由不同的Spring模块以不同方式处理。例如, Spring Data JPA
将处理 @Repository
,并将尝试用实现替换任何标记为此注释的接口。 Spring还将对这些类应用自动异常转换。另一个例子, Spring Web MVC
进程 @Controller
,并在URL映射中使用用它标记的类。
Second reason: some of this annotations processed differently by different Spring modules. For example, Spring Data JPA
will process @Repository
, and will try to replace with implementation any interface marked by this annotaion. Spring also will apply automatic exception translation to such classes. Another example, Spring Web MVC
process @Controller
, and use classes marked with it in URL mappings.
实际上,在未来的版本中,Spring的某些模块可以特殊方式处理 @Service
。不那么简单 @Component
。这就是文档建议的原因:
Actually, in future versions, some modules of Spring could process @Service
in particular way. Not as simple @Component
. That's why documentation advice:
这篇关于如果我们在spring MVC中交换@service和@repository注释会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!