Member-only story
The Evolution of Dependency Injection: From XML to Constructor Injection in Spring
Dependency Injection (DI) is one of the most important ideas in the Spring Framework. It helps make code cleaner, easier to test, and less dependent on hard-coded connections between classes. Over time, the way developers use DI in Spring has changed a lot — starting with large XML files and moving to neat and simple constructor injection.
In this article, we’ll walk through this journey step-by-step, using very simple English and easy code examples so that even someone new to Spring can understand.
What is Dependency Injection?
Imagine you have a Car class. The car needs an Engine to work. Without DI, the Car might create the Engine itself:
public class Car {
private Engine engine;
public Car() {
this.engine = new Engine(); // Direct creation
}
}This is not flexible. What if we want a different type of engine later? We would have to change the Car class.
Dependency Injection means we don’t create the Engine inside the Car. Instead, we “inject” it from outside. This way, the Car doesn’t care how the Engine is made — it just receives it.