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

查看:47
本文介绍了如果我们在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 are just specializations of @Component annotation. So, generally, they can be used one instead of other. But ... you should not do this.

第一个原因:这些注释中的任何一个都明确了您的组件在应用程序中的作用.显示 - 此组件是否属于控制器、服务或数据层.

First reason: any of these annotations make clear the role of your component in the application. Shows - is this component belongs to the controller, service, or data layer.

第二个原因:其中一些注解被不同的 Spring 模块以不同的方式处理.例如,Spring Data JPA 将处理 @Repository 并尝试用实现替换此注解标记的任何接口.Spring 还将对此类类应用自动异常转换.另一个例子:Spring Web MVC处理@Controller,并在URL映射中使用用它标记的类.

Second reason: some of these 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 annotation. Spring also will apply automatic exception translation to such classes. Another example: Spring Web MVC processes @Controller, and uses classes marked with it in URL mappings.

实际上,在未来的版本中,Spring 的某些模块可以以特定方式处理 @Service.不像@Component那么简单.这就是文档建议的原因:

Actually, in future versions, some modules of Spring could process @Service in a particular way. Not as simple @Component. That's why documentation advises:

@Repository、@Service 和@Controller 也有可能在 Spring Framework 的未来版本中携带额外的语义.因此,如果您在使用 @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天全站免登陆