This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Spring and the fly likes Why interface is injected instead of class in Spring MVC Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Frameworks » Spring
Bookmark "Why interface is injected instead of class in Spring MVC" Watch "Why interface is injected instead of class in Spring MVC" New topic
Author

Why interface is injected instead of class in Spring MVC

shivang sarawagi
Ranch Hand

Joined: Jun 19, 2008
Posts: 147
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
internet detective
Marshal

Joined: May 26, 2003
Posts: 30138
    
150

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.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
shivang sarawagi
Ranch Hand

Joined: Jun 19, 2008
Posts: 147
Thanks for the reply. What if the interface is implemented by more than one class. Which class will Spring inject at runtime??
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30138
    
150

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why interface is injected instead of class in Spring MVC
 
Similar Threads
Spring 3.0 MVC - Not getting to the Controller.java
Neither BindingResult nor plain target object for bean name 'command' available as request attribute
Hibernate with Spring
Why we Use Service Facde pattern with Hibernate?
Spring MVC