Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
833 views
in Technique[技术] by (71.8m points)

spring - Where should @Service annotation be kept? Interface or Implementation?

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...