如果我们在spring MVC中交换@service和@repository注解会发生什么

zphenhs4  于 7个月前  发布在  Spring
关注(0)|答案(3)|浏览(80)

为什么我们需要在服务实现中使用@service,在DAO实现中使用@repository。当我在spring MVC中交换@service@repository annotation时,没有出现任何问题。

8e2ybdfx

8e2ybdfx1#

根据文档@Repository@Service@Controller都是同义词。它们都只是@Component注解的特殊化。所以,通常,它们可以用一个代替另一个。但是.你不应该这样做。
第一个理由:这些注解中的任何一个都 * 清楚地表明了你的组件在应用程序中的角色 *。显示-这个组件属于控制器层、服务层还是数据层。
第二个原因:其中一些annotation由不同的Spring模块以不同的方式处理。例如,Spring Data JPA将处理@Repository,并将尝试使用implementation替换此annotation标记的任何接口。Spring还将对此类类应用自动异常转换。另一个示例:Spring Web MVC处理@Controller,并在URLMap中使用标记为它的类。
实际上,在未来的版本中,Spring的一些模块可以以特定的方式处理@Service。而不是简单的@Component。这就是为什么文档建议:
在Spring Framework的未来版本中,@Repository、@Service和@Controller也可能携带额外的语义。因此,如果您在使用@Component或@Service作为服务层之间进行选择,@Service显然是更好的选择。

3lxsmp7m

3lxsmp7m2#

这取决于你在框架的其余部分使用了什么。理论上没有什么变化,因为@Service@Repository注解基本上是@Component注解。对于@Controller@Endpoint也是如此(对于Spring Ws,还有更多)。
然而,它们表达了类是什么(服务、存储库)的意图,并向用户明确了该类属于哪一层。
但是,如果您还使用Spring进行事务管理,那么@Repository也是adding exception translation到该类的触发器(另请参阅参考指南)。
虽然没有什么 * 必须 * 打破它可能会在某个时候。

nwo49xxi

nwo49xxi3#

根据文件

Service.java

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
  @AliasFor(annotation = Component.class)
  String value() default "";
}

Repository.java

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
  @AliasFor(annotation = Component.class)
  String value() default "";
}

所以在阅读文档后,我们似乎不会立即得到错误,理论上是可能的,但这不是好的做法。如果在未来的Spring官方添加新的代码行,那么我们可能会得到错误。

相关问题