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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…