Where should @Service annotation be kept? Interface or Implementation?
Basically annotations like @Service, @Repository, @Component, etc. they all serve the same purpose:
auto-detection when using annotation-based configuration and classpath scanning.
From my experience I am always using @Service
annotation on the interfaces or abstract classes and annotations like @Component
and @Repository
for their implementation. @Component
annotation I am using on those classes which serves basic purposes, simple Spring beans, nothing more. @Repository
annotation I am using in the DAO
layer, for e.g. if I have to communicate to the database, have some transactions, etc.
So I would suggest to annotate your interface with the @Service
and other layers depending on the functionality.
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,- 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,
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