The benefit of using Injection Dependency occurs when you have code similar to the following
Interface i; if (useA) { i = new A(); } else if (useB) { i = new B(); } else if (useC) { i = new C(); } i.call();
You have several different types of Interface
, and you need to choose which one to use when starting the program, because you do not know which one should be used when writing the program. This means that when you run the program, you must define useA
, useB
and useC
. A typical approach is to have a discovery code or a properties file that loads, setting these values.
In addition, the “who actually does this” part can be a daunting task, for example, web applications, which are mainly composed of code that is called externally.
Dependency injection formalizes this as:
@Injection Interface i; i.call();
Spring automatically initializes i
, so you don’t have to worry in your code about flags or where to put the factory in the standard way. This separation of A, B, C processing from the actual code has proven that it creates very clean code.
EDIT: when repeating this question, I realized that the question is actually “why use dependency injection when you can do the same with getters and seters?”.
In my opinion, it is important to understand that you can no longer inject dependencies than you can with getters and setters, but the only place you can use getters and setters is the code that creates the new object. In Java, this is the new
operator. In other words, the code must know all the details, and often this is not so. That is why we have factories of factories - as a means to bring the decision-making process closer to lead time - and dependency injection is basically like that. A factory. But it is important to note that it allows you to separate part of the configuration from the part that performs the work, and place it in another place.
Thorbjørn Ravn Andersen
source share