English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Spring Dependency Injection

Dependency Injection (DI) is a design pattern that can remove dependencies from programming code to make it easy to manage and test applications. Dependency Injection makes our programming code loosely coupled. To better understand DI, let's first understand dependency resolution (DL):

Dependency resolution

Dependency lookup is a method of obtaining resources after the requirement. For example, there can be multiple ways to obtain resources:

A obj = new AImpl();

Thus, we can obtain resources directly through the new keyword (an instance of class A). Another method is the factory method:

A obj = A.getA();

Thus, we obtain resources by calling the static factory method getA().

Alternatively, we can obtain resources through JNDI (Java Naming and Directory Interface). :

Context ctx = new InitialContext();
Context environmentCtx = (Context) ctx.lookup("java:comp"/env);
A obj = (A) environmentCtx.lookup("A");

There can be multiple ways to obtain resources to obtain resources. Let's look at the problems of this method.

Dependency resolution issues

There are mainly two dependency resolution issues.

Tightly coupled: The dependency resolution method makes the code tightly coupled. If the resources are changed, a large number of modifications to the code are required. Testing is not easy: This method can cause many problems when testing application programs, especially in black-box testing.

Dependency Injection

Dependency injection is a design pattern that eliminates code. In this case, we provide information from an external source (such as an XML file). It makes our code loosely coupled and easier to test. In this case, we write the code as:

class Employee{
Address address;
Employee(Address address){
this.address = address;
}
public void setAddress(Address address){
this.address = address;
}
}

In this case, the instance of the Address class is provided by an external source (such as an XML file) through the constructor or setter method.

Two methods to perform dependency injection in the Spring framework

The Spring framework provides two methods for injecting dependencies

Through Constructor Through Setter Method