Spring - Dependency Injection (DI)
DI is a framework which provides loose coupling in code. Here loose coupling means no hard coding of the object. Instead of hard coding, we will be injecting these object from some configurations (XML based, java based, annotation-based).
DI is nothing but design patterns which give you the lightweight loosely couple enterprise application in the result.
What is an injection? -- Inserting of an object/ value into a class whenever the help requires it of third party configurations.
There is two way of achieving Dependency Injection:
- By Constructor
- By Setter method
Constructor Injection: Injecting any object/ value through the constructor of a class. For, e.g., I have a Test class with the parameterized constructor in it, and I am initializing parameter of that constructor from the external source, i.e. XML file. See how
public class Test {
private int id;
public Test(int id) {
this.id = id;
}
}
XML configuration file: //here now 100 will be assigned to the id of Test class
Setter method Injection: Injecting any object/ value through the setter method of a class. For, e.g., I have a Test class with setter method in it, and I am initializing parameter of that setter method from the external source, i.e. XML file. See how
public class Test {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
XML configuration file: //here now 100 will be assigned to the id of Test class
Please add on comments and like this lesson, if it gave you some revision or refreshment on Spring - Dependency Injection (DI) concepts.