• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Liutauras Vilda
  • Paul Clapham
Sheriffs:
  • paul wheaton
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Piet Souris
Bartenders:
  • Mike London

Why interface is injected instead of class in Spring MVC

 
Ranch Hand
Posts: 159
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
author & internet detective
Posts: 41502
881
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 159
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Posts: 41502
881
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic