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

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...