---
title: "IoC and dependency injection"
chapter: "02"
---

# IoC and dependency injection

Dependency injection separates **using** an object from **constructing** it.

## How beans enter the container

- `@Bean` methods in `@Configuration` classes.
- Component scanning of `@Component`, `@Service`, `@Repository`, and
  `@Controller`.
- Framework and Boot auto-configuration.
- Programmatic registration for specialized cases.

Prefer explicit package boundaries and focused configuration. Scanning an
entire organization package makes accidental beans harder to see.

## Constructor injection

Constructor injection is normally the best default. Required dependencies are
visible, final fields are possible, and tests can construct the class directly.
Avoid field injection because it hides dependencies and couples tests to the
container.

## Multiple candidates

If two beans implement one interface, Spring needs help. Use one `@Primary`,
use `@Qualifier` at the injection point, or redesign the boundary. A qualifier
describes meaning better than relying on a bean name.

## Circular dependencies

If A needs B and B needs A, the design may mix responsibilities. Break the
cycle with a third service, domain event, or clearer direction. Do not hide a
bad boundary with lazy injection unless the lifecycle truly demands it.

## Optional dependencies

Use `Optional`, `ObjectProvider`, or conditional configuration only when the
capability is genuinely optional. Required business collaborators should fail
fast at startup.

## Feynman check

The container is a seating planner. Constructors say who must sit together.
Qualifiers distinguish two people with the same job. A circular dependency is
two people each refusing to sit until the other sits first.
