Lesson 1 of 9 · 24m
Dependency Injection That Survives Scale
Use constructor injection, explicit boundaries, and narrow bean definitions so the object graph remains testable and operable years later.
The first large Spring system I inherited had 1,400 beans and no owner who could say which ones mattered. Nothing was obviously broken, but every change took a week because constructors lied, circular dependencies were hidden behind field injection, and configuration classes had become junk drawers. Dependency injection is not magic plumbing. It is the architecture of object ownership.
Constructor injection is the default because it tells the truth
A constructor declares what a class cannot live without. If the list is uncomfortable, the class is probably doing too much:
@Service
public class InvoiceService {
private final InvoiceRepository invoices;
private final PaymentClient payments;
private final Clock clock;
public InvoiceService(InvoiceRepository invoices,
PaymentClient payments,
Clock clock) {
this.invoices = invoices;
this.payments = payments;
this.clock = clock;
}
}That Clock looks trivial until a refund window test needs deterministic time. Injecting time, randomness, and external clients is what separates unit tests from ceremonies.
Field injection hides coupling
This still compiles, but it makes tests worse and dependencies invisible:
@Service
public class BadInvoiceService {
@Autowired private InvoiceRepository invoices;
@Autowired private PaymentClient payments;
}You cannot construct it without reflection or a Spring context. You cannot see coupling in the API. final is impossible. On day one it saves six lines; in year three it costs architectural clarity.
Be suspicious of bean-count growth
A healthy application has a small number of architectural roles: controllers, application services, repositories, integration clients, schedulers, and configuration adapters. Dozens of @Component classes named Helper, Util, or Manager usually mean responsibilities were never assigned.
Circular dependencies are especially important. Spring sometimes detects them only when proxies or lazy initialization shift. Treat any circularity as a design defect: one side owns a policy, the other owns a mechanism, or a third object is missing.
Field notes
- Constructor explosion is a signal, not a style violation; split orchestration from domain decisions.
- Avoid
@Autowiredon fields and avoid@Lazyas a permanent treatment for circular dependencies. - Inject
Clock,SecureRandomwrappers, and external clients; do not inject static singletons and hope tests behave. - Keep framework annotations out of core domain logic where practical. Ports can survive framework upgrades better than annotated business models.
- When two beans of the same type exist, make the caller choose explicitly with a qualifier instead of relying on accidental name matching.
Was this lesson helpful?