core

Dependency Injection

Let the framework wire object dependencies instead of constructing them by hand — for testability and loose coupling.

Dependency Injection is the idea at the heart of Spring: instead of a class constructing the collaborators it needs with new, those collaborators are supplied to it from outside. Hard-coded construction welds a class to specific implementations and makes it nearly impossible to test in isolation, because you cannot swap a real database or HTTP client for a fake. DI inverts the control of creation — hence "Inversion of Control" — so the framework, not the class, decides what concrete dependency to hand over.

Instead of a chef growing their own vegetables, the kitchen receives them from a supplier. Swap suppliers without changing the recipe.

Key Concepts

1
In Spring, you mark classes as beans with @Component, @Service, @Repository, or @Configuration, and Spring's container scans for them, instantiates them, and stores them in the ApplicationContext. When a bean needs another, Spring injects it — by constructor (the strongly preferred form), by setter, or by field. Constructor injection is preferred because it makes dependencies explicit and mandatory, allows the field to be final, and yields an object that is fully initialised and testable with a plain new in a unit test, no Spring required. Field injection, by contrast, hides dependencies and can only be satisfied through reflection, which is why it is discouraged.
@Component@Service@Repository@ConfigurationApplicationContext
2
The practical payoffs are testability and loose coupling: a service depending on a PaymentGateway interface can be handed a mock in tests and the real implementation in production without changing a line. The points interviewers probe are why constructor injection beats field injection, how Spring resolves ambiguity when several beans match a type (@Qualifier, @Primary), and the distinction between DI as a principle and the container as the mechanism that realises it.
PaymentGateway@Qualifier@Primary