File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Spring and the fly likes Dependency injection vs Singleton pattern Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Frameworks » Spring
Bookmark "Dependency injection vs Singleton pattern" Watch "Dependency injection vs Singleton pattern" New topic

Dependency injection vs Singleton pattern

Manikandan Swaminathan
Ranch Hand

Joined: Aug 10, 2008
Posts: 117
Hi ranchers,

Nowadays, i am coming across many instances where people/developers are willing to use dependency injection rather than singleton classes/patterns?Can the dependency injection be really used in all the places/situations where a singleton class is needed?
Need your thoughts/suggestions on this.

Nathan Pruett

Joined: Oct 18, 2000
Posts: 4121

The Singleton pattern is mostly considered an *anti*-pattern now. Static creation makes it difficult to test and, if suddenly the class doesn't need to be a singleton anymore, requires lots of changes, because you have to change how all the users of the class get the reference.

Dependency injection can create singleton objects in an application through only configuration. The DI container handles the creation of classes and passing references to users of the class around - so the class doesn't need to define static creation methods; and users of the class don't have to know it's a singleton to get a reference, it's reference is just passed to the class like any other dependency.

Write once, run anywhere, because there's nowhere to hide! - /. A.C.
John Pradeep.v
Ranch Hand

Joined: Jul 21, 2008
Posts: 59
Adding to what Nathan said, leaving the object creation strategy to a Dependency injection container makes it easy to inject mock version of the dependencies and test the class under isolation.
Nevertheless, the DI framework can be instructed to maintain a single instance of the class...
I agree. Here's the link:
subject: Dependency injection vs Singleton pattern
It's not a secret anymore!