Inversion of Control (IoC) is the principle that a container, not your code, creates objects and manages them. In Spring that container is usually an ApplicationContext. Dependency Injection (DI) is how Spring puts IoC into practice. An object declares what it needs, and the container passes those dependencies in.
// Without DI - tight coupling
public class UserService {
private UserRepository userRepository = new UserRepository(); // Tight coupling
}
// With DI - loose coupling
public class UserService {
private UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository; // Dependency injected
}
}
In the first class, UserService builds its own UserRepository with new, so the two are tightly coupled. You cannot swap in another implementation or a test mock without editing the class.
In the second class, the dependency arrives through the constructor. Spring chooses what to inject, and a unit test can pass a mock. That is loose coupling.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓