File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » EJB Certification (SCBCD/OCPJBCD)
Bookmark "Best practice about dependency injection" Watch "Best practice about dependency injection" New topic

Best practice about dependency injection

Himai Minh
Ranch Hand

Joined: Jul 29, 2012
Posts: 1120
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

Joined: Mar 17, 2012
Posts: 989
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
Saloon Keeper

Joined: Apr 07, 2010
Posts: 2099

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


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

I agree. Here's the link:
subject: Best practice about dependency injection
jQuery in Action, 3rd edition