Dependency Injection
dependency injection dependency injection (di) is the cornerstone of spring — objects receive their collaborators from the container instead of creating them.
Introduction
Dependency Injection (DI) is the cornerstone of Spring — objects receive their collaborators from the container instead of creating them. It enables testability, loose coupling and clean architecture.
Informative example
Constructor injection — the Spring-recommended style:
@Servicepublic class OrderService {private final OrderRepository repo;private final PaymentGateway gateway;// Constructor injection — fields are final, easy to testpublic OrderService(OrderRepository repo, PaymentGateway gateway) {this.repo = repo;this.gateway = gateway;}public Order place(OrderRequest req) {var order = repo.save(new Order(req));gateway.charge(order);return order;}}// Test — no Spring context neededvar service = new OrderService(mockRepo, mockGateway);
Best practices
- Prefer constructor injection — fields can be
final. - Avoid field injection (
@Autowiredon fields) — hard to test. - Program to interfaces; let Spring pick the implementation.
Purpose of this lesson
Master Dependency Injection so you can apply it confidently in production Java code, technical interviews, and code reviews.
Step-by-step explanation
- Understand the core idea behind Dependency Injection.
- Walk through the runnable example and tweak it in the playground.
- Apply the pattern in a small Spring Boot or CLI exercise of your own.
- Re-read the common mistakes and interview Q&A to lock the concept in.
Interactive workflow diagram
Component scan
@Component, @Service, @Repository discovered.
Debugging tips
- Read the full stack trace — Java's exception messages name the offending class and line.
- Reproduce in the smallest possible
main()method before fixing in the real app. - Use IntelliJ's debugger breakpoints and 'Evaluate Expression' rather than scattering
System.out.
Optimization strategies
- Profile before optimizing — JFR (Java Flight Recorder) and async-profiler reveal real hotspots.
- Prefer immutable data and stream pipelines over hand-rolled loops when readability matters.
- Reach for the right JDK collection (ArrayList vs LinkedList vs ArrayDeque) before writing custom data structures.
Enterprise example
Teams at Netflix, Uber and Goldman Sachs apply Dependency Injection daily — usually wrapped behind Spring Boot services with observability hooks (Micrometer + OpenTelemetry).
Interview questions & answers
Q1Explain Dependency Injection in one minute.
Q2When would you avoid Dependency Injection?
Summary
In this lesson you learned Dependency Injection — the concept, syntax, a runnable example, and the production pitfalls to avoid. Apply it in the playground before moving on.