• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why interface is injected instead of class in Spring MVC

 
shivang sarawagi
Ranch Hand
Posts: 157
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am reading the Spring Hibernate CRUD tutorial from this url

http://viralpatel.net/blogs/spring3-mvc-hibernate-maven-tutorial-eclipse-example/

Please can anyone tell me why in ContactController.java ContactService interface is autowired instead of the class ContactServiceImpl.

Similarly in ContactServiceImpl ContactDAO interface is injected. Shouldn't we supposed to inject class instead of an interface?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34071
331
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
At runtime, the class (implementation) is injected. Spring sees you only have a single implementation of that interface and auto-wires it in.

As for why doing this: using an interface makes testing easier (to mock out the interface), lets you write the front end before the back end is done and lets you substitute in another implementation later. In a nutshell, it makes your code more flexible.
 
shivang sarawagi
Ranch Hand
Posts: 157
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply. What if the interface is implemented by more than one class. Which class will Spring inject at runtime??
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34071
331
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to use a @Qualifier to tell it in that case. If you don't specify, the app will fail because it won't know what to do.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic