Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 119 ยท Spring Framework

Dependency Injection and Inversion of Control

Learn dependency injection in Java - why tight coupling hurts, constructor vs setter vs field injection, a working DI container built with reflection, and Spring's version.

Every non-trivial class depends on others. A checkout service needs a payment gateway and a mailer; a report needs a repository and a clock. The question is who creates those collaborators. If the class creates them itself, it is welded to one implementation forever. If it receives them from outside, it can be tested with fakes, reconfigured for production and reused. Receiving collaborators from outside is dependency injection (DI), and it is the foundation Spring is built on.

In this lesson you will refactor tightly coupled code into injected code, wire an application by hand, and test it with fakes. Then you will build a real DI container in about 60 lines of reflection code: it reads constructors, resolves interfaces, caches singletons, injects lists and detects circular dependencies. Finally you will see the same application in Spring and know exactly what the framework is doing for you. The Spring Framework Introduction explains where DI fits in the bigger picture; Reflection and Annotations cover the Java features the container uses.

The problem: hard-wired dependencies

Here is a typical first version of a checkout service:

Java
public class CheckoutService {
    private final StripeGateway payments = new StripeGateway("sk_live_...");
    private final SmtpMailer mailer = new SmtpMailer("smtp.example.com", 587);

    public Receipt checkout(String customer, int cents) {
        boolean paid = payments.charge(customer, cents);
        mailer.send(customer, paid ? "Thanks for your order" : "Payment failed");
        return new Receipt(customer, cents, paid);
    }
}

It works, and it has four problems:

  • You can't test it without charging a real card and sending a real email.
  • You can't change it without editing it: switching payment providers, or using a different mailer in staging, means changing this class.
  • Configuration is buried inside the class (the API key and SMTP host), mixed with business logic.
  • Its needs are hidden. Nothing in its public API says it talks to Stripe and an SMTP server.

The fix has two steps. First, depend on interfaces that describe what the class needs (PaymentGateway, Mailer) instead of concrete classes. This is the dependency inversion principle from Object-Oriented Design Principles (SOLID). Second, receive the implementations through the constructor:

Java
public class CheckoutService {
    private final PaymentGateway payments;
    private final Mailer mailer;

    public CheckoutService(PaymentGateway payments, Mailer mailer) {
        this.payments = payments;
        this.mailer = mailer;
    }
    // checkout(...) unchanged
}

Now the class states its dependencies in its constructor, and whoever creates it decides which implementations to pass in.

Three ways to inject

Style How Verdict
Constructor injection Dependencies are constructor parameters, stored in final fields. The default choice. Required dependencies are explicit, the object is complete and immutable after construction, and tests can call new directly.
Setter injection A setMailer(Mailer) method is called after construction. For genuinely optional dependencies or ones that must change at runtime. The object can exist half-configured.
Field injection The framework writes directly into a (often private) field, e.g. @Autowired private Mailer mailer; Avoid. Hides dependencies, prevents final, and makes the class impossible to create correctly without the framework or reflection.

Constructor injection has one more benefit: it makes design problems visible. A constructor with nine parameters is uncomfortable to write, and that discomfort is telling you the class does too much.

Manual wiring and testing with fakes

You don't need a framework to use DI. Creating the object graph by hand in one place, usually main, is called pure DI, and the place itself is the composition root. Tests become their own small composition roots that plug in fakes. Run this example: main wires a "production" graph and then runs JUnit tests that wire fakes.

Java Constructor injection, a composition root and tests with fakes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The tests use lambdas as fakes because both interfaces have a single method. Notice the third test: the fake gateway fails the test if it is called at all. Those tests run in milliseconds and need no network, database or framework. That is the real payoff of DI: not the framework, but classes that don't decide their own collaborators. Test Doubles and Mockito goes deeper into fakes, stubs and mocks.

Pure DI is a perfectly good choice for small applications and libraries. It becomes tedious as the graph grows: hundreds of classes, each created in the right order, some shared and some not, some needing configuration values. That bookkeeping is what a DI container automates.

Building a DI container with reflection

A container needs to answer one question recursively: "how do I build an instance of this type?" The answer:

  1. If the type is an interface, find out which class implements it (a binding).
  2. Choose a constructor of that class.
  3. Build an instance of each constructor parameter type, by asking step 1 again.
  4. Call the constructor, cache the result (singleton), return it.

Java's reflection API gives us everything needed: getDeclaredConstructors(), getParameterTypes(), isAnnotationPresent() and newInstance(). Our container also honors a custom @Inject annotation to pick a constructor when a class has several, as Spring's @Autowired and Jakarta's @Inject do.

Java A DI container in 60 lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read the indented trace from the bottom up. To build the controller, the container needed a GreetingService, which needed a repository and a time source; then the AuditLog needed the time source again, and got the same instance ("reuse"). The controller has two constructors, and @Inject picked the right one. Nowhere in the application code is there a new for a collaborator. The last line shows that asking by interface or by implementation class returns the same singleton, because the cache is keyed by the implementation.

This is, in miniature, what Spring's DefaultListableBeanFactory does. The real thing adds bean definitions, scopes, lifecycle callbacks, proxies, configuration values and thousands of edge cases, but the core recursion is the same.

Resolving by type: lists, ambiguity and cycles

Our first container needed an explicit bind() for every interface. Spring usually works the other way around: it knows a set of components (found by component scanning) and resolves a dependency by type, picking the one registered class that fits. That raises three new situations:

  • Several candidates. Two classes implement Notifier. For a single Notifier parameter, that is ambiguous, and Spring fails with "expected single matching bean but found 2". For a List<Notifier> parameter, Spring injects all of them.
  • No candidate. Spring fails at startup with "No qualifying bean of type ... available".
  • A cycle. A needs B and B needs A. With constructor injection this can never be satisfied, and the container must detect it rather than recurse forever.

The second container handles all three. It reads generic parameter types (List<Notifier>) with getGenericParameterTypes() and keeps a stack of the classes currently being created to detect cycles.

Java By-type resolution, List injection and cycle detection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The error messages are deliberately close to Spring's, because you will meet them all. Ambiguity is solved with @Primary or @Qualifier, covered in Beans, Configuration and Component Scanning. A cycle is almost always a design problem: Billing, Invoices and Customers know too much about each other. Break it by extracting the shared logic into a new class, or by publishing an event instead of calling back. Spring Boot has refused circular references by default since version 2.6 (spring.main.allow-circular-references=false) for exactly this reason.

The same application in Spring

Here is the greeting application from the container example, written for Spring. The classes keep their constructors; the annotations replace our bind() calls:

Java
@Repository
class InMemoryGreetingRepository implements GreetingRepository { ... }

@Component
class SystemTimeSource implements TimeSource {
    public int hour() { return LocalTime.now().getHour(); }
}

@Service
class GreetingService {
    private final GreetingRepository repository;
    private final TimeSource time;

    GreetingService(GreetingRepository repository, TimeSource time) {   // no @Autowired needed
        this.repository = repository;
        this.time = time;
    }
    ...
}

@RestController
class GreetingController {
    private final GreetingService service;

    GreetingController(GreetingService service) {
        this.service = service;
    }

    @GetMapping("/greet")
    String greet(@RequestParam String name, @RequestParam(defaultValue = "en") String language) {
        return service.greet(name, language);
    }
}

What Spring does at startup maps directly onto your container:

Your container Spring
new Container(EmailNotifier.class, ...) Component scanning finds @Component, @Service, @Repository, @Controller classes
bind(Interface, Impl) Not needed when exactly one bean implements the interface; otherwise @Primary / @Qualifier
choose the only constructor, or the @Inject one the same rule: a single constructor is used automatically; with several, mark one with @Autowired (or jakarta.inject.Inject)
List<Notifier> gets all candidates the same, ordered by @Order; Map<String, Notifier> gets them keyed by bean name
singleton cache default singleton scope
"No qualifying bean", "expected single matching bean", cycle error NoSuchBeanDefinitionException, NoUniqueBeanDefinitionException, BeanCurrentlyInCreationException

One important difference: Spring creates all singletons eagerly at startup, not on first use. Wiring errors therefore crash the application immediately, during deployment, instead of on the first request that happens to need a broken bean.

Optional and lazy dependencies

Sometimes a dependency may legitimately be missing (a metrics client that is only configured in production), or you want a new instance on each use. Spring supports three idioms:

Java
// 1. Optional dependency
GreetingService(GreetingRepository repository, Optional<MetricsClient> metrics) { ... }

// 2. ObjectProvider: look up lazily, optionally, or get a fresh prototype each time
GreetingService(ObjectProvider<MetricsClient> metrics) {
    this.metrics = metrics;
}
void record() {
    metrics.ifAvailable(client -> client.increment("greetings"));
}

// 3. Setter injection for a truly optional collaborator
@Autowired(required = false)
void setMetrics(MetricsClient metrics) { this.metrics = metrics; }

DI anti-patterns

  • Service locator. Calling applicationContext.getBean(Mailer.class) inside business methods. The dependency is hidden again, and the class now depends on Spring. Inject what you need instead.
  • Field injection with @Autowired. It works, but the class can't be created correctly in a plain unit test, and its dependencies are invisible from the outside. IntelliJ and Sonar both warn about it.
  • new for collaborators inside services. Creating value objects, DTOs and collections with new is fine. Creating services (anything with I/O or that you would fake in a test) is what DI is meant to stop.
  • Static singletons. PaymentGateway.getInstance() is a global variable in disguise; tests can't replace it.
  • Injecting configuration everywhere. Instead of passing the whole Environment into a class, inject the specific values or a typed configuration object (see Configuration, Properties and Profiles).

DI is not unique to Spring. Jakarta EE uses CDI (@Inject, @ApplicationScoped), Google's Guice uses explicit modules much like our first container, and Dagger and Micronaut generate the wiring code at compile time instead of using reflection at startup. The principles in this lesson apply to all of them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is constructor injection preferred over field injection?

    A constructor documents what the class needs and guarantees a fully initialized object. Field injection hides dependencies and needs a framework to set them.
  2. 2. In the first container, AuditLog and GreetingService both need a TimeSource. How many FixedTimeSource objects are created?

    The container caches every instance it creates, so the second request for TimeSource reuses the first object. The trace shows "reuse FixedTimeSource".
  3. 3. Two beans implement Notifier, and a constructor asks for List<Notifier>. What does Spring inject?

    For collection types, Spring injects all matching beans. Only a single-valued Notifier parameter would be ambiguous.
  4. 4. A(B b), B(C c), C(A a), all using constructor injection. What happens when the container builds A?

    No order of constructor calls can satisfy the cycle, so a good container detects it and fails with the path. Fix the design rather than the configuration.
  5. 5. Which of these is the service locator anti-pattern?

    Looking dependencies up from the container hides them and ties the class to the framework. Inject them instead.

Summary

  • Dependency injection means a class receives its collaborators instead of creating them; it is the form of inversion of control Spring is built on.
  • Depend on interfaces and inject implementations through the constructor. Use setters only for optional dependencies; avoid field injection.
  • Pure DI wires everything by hand in a composition root; tests plug in fakes the same way.
  • A DI container resolves types recursively: bindings for interfaces, constructor selection, recursive parameter resolution and a singleton cache. Reflection makes it possible.
  • Resolution by type must handle lists (inject all), ambiguity (fail, or use @Primary/@Qualifier), missing beans and cycles (fail with the path).
  • Spring does the same with component scanning, eager singleton creation at startup and precise errors. Avoid the service locator, static singletons and new for services.

Next: Beans, Configuration and Component Scanning shows every way to define Spring beans, their scopes and lifecycle, and how to choose between several candidates.