Skip to main content

IoC and Dependency Injection

The entire architectural foundation of Spring rests upon two theoretical concepts: Inversion of Control (IoC) and Dependency Injection (DI). Dependency Injection is simply the practical implementation of the broader IoC principle.

Inversion of Control (IoC)

In standard programming, your custom code directly controls the execution flow. If your application needs to connect to a database, your code manually calls new DatabaseConnection(), essentially controlling the objects it depends on.

Inversion of Control flips this relationship. Instead of your custom code calling the framework, the framework calls your custom code. It acts as a massive "Container" that manages the lifecycles, configuration, and destruction of objects. You simply define the rules, and the IoC Container manages the flow.

Dependency Injection (DI)

Dependency Injection is how the Spring IoC Container resolves class dependencies.

If Class A requires an instance of Class B (a database connection) to function, Class A has a "Dependency" on Class B. Normally, Class A would instantiate Class B itself.

// TIGHT COUPLING: Hard to test!
public class UserService {
private DatabaseConnection db = new MySQLConnection(); // Hardcoded dependency!

public void saveUser() { db.save(); }
}

With Spring DI, you never use the new keyword for primary services. You simply declare that you need the dependency, and the Spring Container automatically "injects" the correct instance into your class at runtime.

// LOOSE COUPLING: Spring handles the injection!
@Service
public class UserService {
private final DatabaseConnection db;

// Spring sees this constructor and injects the dependency automatically
@Autowired
public UserService(DatabaseConnection db) {
this.db = db;
}

public void saveUser() { db.save(); }
}

By decoupling the creation of objects from the usage of objects, you gain massive testability. During Unit Testing, you can easily mock the DatabaseConnection interface and inject the fake mock via the constructor!