@Service批注应保存在哪里?接口还是实现? [英] Where should @Service annotation be kept? Interface or Implementation?
问题描述
我正在使用Spring开发应用程序.我需要使用@Service
批注.我有ServiceI
和ServiceImpl
这样的ServiceImpl implements ServiceI
.我对在哪里保留@Service
批注感到困惑.
I'm developing an application using Spring. I'm required 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
). (IMHO)仅具有一个接口和仅一个实现该接口的类是无用的,并且违反了 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 Bean,并且
- 有一个注入点,该注入点使用该接口进行基于类型的注入,
@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存储库接口完全不同
这篇关于@Service批注应保存在哪里?接口还是实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!