aspose file tools*
The moose likes EJB Certification (SCBCD/OCPJBCD) and the fly likes Best practice about dependency injection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » EJB Certification (SCBCD/OCPJBCD)
Bookmark "Best practice about dependency injection" Watch "Best practice about dependency injection" New topic
Author

Best practice about dependency injection

Himai Minh
Ranch Hand

Joined: Jul 29, 2012
Posts: 812
    
    1
From Spring in Action, p.8

That's the key benefit of Dependency Injection - loose coupling.If an object only knows about its dependencies by their interface (not by its implementation or how they are instantiated), then the dependency can be swapped out with a different implementation without the depending object knowing the difference.


Is it always a best practice to inject an object by its interface instead of its class?
Use the example on Frits notes p.66,


This is not a good practice as OtherServlet knows the implementation of the object:


Any comments?
E Armitage
Rancher

Joined: Mar 17, 2012
Posts: 892
    
    9
Yes, generally you want to code to the interface rather than the implementation. Also it is possible for implementation classes to only be available at run time and not at compile time making the second option impossible to use anyway.
In the EJB world, EJB 3.1 made business interfaces optional to ease the 'burden' on EJB developers of creating an interface every time they create an EJB. I would only use no interface EJBs within a module rather than for inter module communication (module here is intentionally obscure, dependent on the scenario).
In design patterns, facade and adapter are common patterns that need interfaces to work so most designs will likely need interfaces anyway.
Having said that, modern dependency injection mechanisms advertise injecting any POJOs into any POJOs as you don't want to create interfaces with only once off implementations. The idea is that creating interfaces or not should be driven by design decisions (e.g wanting to use a certain pattern) not by whether you want to inject or not.
Frits Walraven
Creator of Enthuware JWS+ V6
Bartender

Joined: Apr 07, 2010
Posts: 1731
    
  25

Is it always a best practice to inject an object by its interface instead of its class?

Yes!

But.... if your EJB doesn't have an interface (no-interface view) you will inject by the bean class name.

Regards,
Frits
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Best practice about dependency injection