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.
Should I annotate the interface or the implementation with @Service
? What are the differences between these two approaches?
I never put @Component
(or @Service
, ...) at an interface, because this make the interface useless. Let me explain why.
claim 1: If you have an interface then you want to use that interface for the injection point type.
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.
fact: When you put:
@Component
(or @Service
, ...) at an interface,then you will get and NoUniqueBeanDefinitionException
(or you have a very special configurations setup, with Environment, Profiles or Qualifiers ...)
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 interfaces are something complete different