@Service 注释应该保存在哪里?接口还是实现? [英] Where should @Service annotation be kept? Interface or Implementation?

查看:79
本文介绍了@Service 注释应该保存在哪里?接口还是实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Spring 开发应用程序.我需要使用 @Service 注释.我有 ServiceIServiceImpl 这样 ServiceImpl 实现 ServiceI.我在这里很困惑我应该在哪里保留 @Service 注释.

I'm developing an application using Spring. I need to use the @Service annotation. I have ServiceI and ServiceImpl such that ServiceImpl implements ServiceI. I'm confused here as to where should I keep the @Service annotation.

我应该用 @Service 注释接口或实现吗?这两种方法有什么区别?

Should I annotate the interface or the implementation with @Service? What are the differences between these two approaches?

推荐答案

我从不把 @Component(或 @Service, ...)放在接口上,因为这使界面无用.让我解释一下原因.

I never put @Component (or @Service, ...) at an interface, because this make the interface useless. Let me explain why.

声明 1:如果您有一个接口,那么您希望将该接口用于注入点类型.

claim 1: If you have an interface then you want to use that interface for the injection point type.

声明 2: 接口的目的是定义一个可以由多个实现实现的契约.另一方面,你有你的注入点(@Autowired).只有一个接口和一个实现它的类是(恕我直言)没用的,并且违反了YAGNI.

claim 2: The purpose of an interface is that it define a contract that can been implemented by several implementations. On the other side you have your injection point (@Autowired). Having just one interface and only one class that implement it, is (IMHO) useless, and violates YAGNI.

事实:当你输入:

  • @Component(或@Service,...)在一个接口上,
  • 有多个实现它的类,
  • 至少有两个类成为 Spring Beans,并且
  • 有一个注入点,使用接口进行基于类型的注入,
  • @Component (or @Service, ...) at an interface,
  • have multiple classes that implements it,
  • at least two classes become Spring Beans, and
  • have an injection point that use the interface for type based injection,

然后你会得到和 NoUniqueBeanDefinitionException(或者您有一个非常特殊的配置设置,包括环境、配置文件或限定符...)

then you will get and NoUniqueBeanDefinitionException (or you have a very special configurations setup, with Environment, Profiles or Qualifiers ...)

结论:如果您在接口上使用 @Component(或 @Service,...),那么您必须至少违反一个两个宗派.因此我认为将 @Component 放在接口级别是没有用的(除了一些罕见的场景).

Conclusion: If you use @Component (or @Service, ...) at an interface then you must violate at least one of the two clains. Therefore I think it is not useful (except some rare scenarios) to put @Component at interface level.

Spring-Data-JPA Repository 接口完全不同

这篇关于@Service 注释应该保存在哪里?接口还是实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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