如果我们在spring MVC中交换@service和@repository注释会发生什么 [英] What will happen if we interchange @service and @repository annotation in the spring MVC

查看:133
本文介绍了如果我们在spring MVC中交换@service和@repository注释会发生什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们需要在服务实现中使用 @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.

推荐答案

根据 documentaion @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:


@ Rebount,@ Service和@Controller也可能
带有额外的语义Spring框架的未来版本。
因此,如果您选择使用@Component或@Service作为服务层
,@ Service显然是更好的选择。

It is also possible that @Repository, @Service, and @Controller may 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.

这篇关于如果我们在spring MVC中交换@service和@repository注释会发生什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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