Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Best practice about dependency injection

 
Himai Minh
Ranch Hand
Posts: 1296
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 989
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 2406
93
Android Chrome Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic