Inversion of Control (IoC) is a design principle where a framework or container, not your own code, controls the creation, wiring and lifecycle of objects and the flow of execution. Instead of a class building its own collaborators with new, something external supplies them. The most common way to apply IoC is dependency injection (DI), and Spring's ApplicationContext is the best-known IoC container in Java.
The result is loosely coupled code that is easier to test, replace and configure. The phrase "Hollywood principle" (do not call us, we will call you) captures the idea: your code is called by the framework.
Without IoC, a class creates and owns its dependencies, which hard-wires it to concrete implementations.
To test OrderService you must deal with a real SMTP sender, and to change the implementation you must edit the class. With IoC, the class declares what it needs and receives it from outside.
Now a test can pass a fake EmailSender, and production code can pass an SMTP or API-based one.
DI is the technique used by Spring, Jakarta CDI, Guice and Micronaut. There are three injection styles.
| Style | Example | Notes |
|---|---|---|
| Constructor injection | OrderService(EmailSender s) | Recommended: immutable fields, required dependencies, easy to test |
| Setter injection | setSender(EmailSender s) | For optional or changeable dependencies |
| Field injection | @Autowired private EmailSender s; | Avoid: hides dependencies and hampers unit tests |
In Spring, a single constructor is enough; no @Autowired is needed.
Spring reads configuration (annotations, Java @Configuration classes or XML), creates beans, resolves their dependencies and manages their lifecycle.
In a Spring Boot application, @SpringBootApplication enables component scanning and auto-configuration, so you rarely create the context yourself. The container instantiates OrderService, finds the EmailSender bean and passes it to the constructor.
DI is not the only form. Each of these also inverts control.
JdbcTemplate calling your row mapper.Benefits:
Trade-offs:
No. IoC is the broad principle. Dependency injection is one way to implement it, specifically for supplying dependencies.
It makes dependencies explicit and required, allows final fields and lets you create the object in a plain unit test without a container.
No. You can apply the principle manually by passing dependencies into constructors, often called pure DI. A container just automates the wiring.
A bean is an object created and managed by the IoC container, for example a class annotated with @Service or returned from a @Bean method.
Inversion of Control moves the responsibility for creating and connecting objects out of your classes and into a container or framework. Dependency injection, especially through constructors, is the practical way to use it. The payoff is decoupled, testable code, at the cost of some indirection.