The 30 second answer
Inversion of control means my classes don't create the objects they depend on; the Spring container creates them and hands them in. Dependency injection is how that happens: the dependency arrives through the constructor, a setter or a field. The benefit is loose coupling. An OrderService depends on a PaymentClient interface, and in tests I can pass a fake one without changing the service.
<!-- level: 1 --> <!-- must_know: true -->
Without IoC, a class builds its own collaborators:
public class OrderService {
private final PaymentClient payments = new StripePaymentClient(); // hard-wired
}That class is tied to one implementation, hard to test and hard to reconfigure. With IoC, the class only declares what it needs, and the container supplies it:
@Service
public class OrderService {
private final PaymentClient payments;
public OrderService(PaymentClient payments) { // injected by Spring
this.payments = payments;
}
}The Spring Framework reference describes IoC as a process where objects define their dependencies only through constructor arguments, factory method arguments or properties, and the container then injects those dependencies when it creates the bean. The control over creating and wiring objects is inverted: it moves from your code to the container.
Why interviewers care: it explains loose coupling (code depends on interfaces), testability (pass a mock or a fake), and one place to configure which implementation is used in each environment.
Sources (2)
- Spring Framework: Introduction to the IoC container and beansdocs.spring.io
- Spring Framework: Dependency injectiondocs.spring.io