Search code examples
javaobjectdependency-injection

Difference between creating new object and dependency injection


What is the difference between creating a new object and dependency injection? Please explain in detail.


Solution

  • Well, creating a new object is as explicit as it can get - you create a new instance of the desired class.

    Dependency injections is a mechanism that provides you with references where you need them. Imagine a class that represents a connection pool to your database - you usually only have one instance of that class. Now you need to distribute that reference to all the classes that use it. Here is where Dependency Injection comes in handy - by using a DI framework such as Spring you can define that the one instance of your pool will be injected into the classes that need it.

    Your question itself is not easy to answer since the creation of an object and dependency injection can't be compared that easily...