Spring dependency injection: how Spring finds and supplies dependencies

Dependency injection means a class receives the objects it needs instead of creating them. Spring does this by matching each constructor parameter, setter or field against its beans by type. This page shows the three injection styles running, how Spring chooses between several matching beans, how to inject lists and maps of beans, and what happens with circular dependencies.

Contents

What dependency injection is

An order service needs a payment gateway and a stock ledger. It could create them itself with new, but then it is tied to those exact classes, it cannot be tested without a real gateway, and every class that needs a gateway builds its own. With dependency injection, the order service only declares what it needs, usually as constructor parameters, and someone else supplies the objects. In a Spring application that someone is the container.

When Spring creates a bean, it looks at each injection point: a constructor parameter, a setter method or a field marked @Autowired. For each one it searches its bean definitions for a bean of a matching type. If exactly one matches, Spring injects it. If none match, startup fails unless the dependency is optional. If several match, Spring narrows them down, mainly by these rules in this order:

  1. A @Qualifier on the injection point, which names the bean to use.
  2. A bean marked @Primary.
  3. Since Spring Framework 6.2, the one bean left when all the others are marked @Fallback.
  4. A bean whose name equals the parameter or field name.

If none of these picks a single bean, startup fails with NoUniqueBeanDefinitionException. Because all of this happens at startup, a missing or ambiguous dependency stops the application before it serves any request, rather than failing later.

Ways to receive a dependency
StyleHowWhen injectedBest for
Constructor injectionConstructor parameters; @Autowired optional for a single constructor since Spring 4.3When the object is createdRequired dependencies, the default choice
Setter injection@Autowired on a setter methodAfter the constructorOptional dependencies, or ones that may be replaced
Field injection@Autowired on a fieldAfter the constructorTest classes; avoid in production code
ObjectProvider<T>Inject the provider, call getObject() or getIfAvailable()When you call itOptional, lazy or prototype dependencies
Collections and mapsList<T> or Map<String, T> parametersWhen the object is createdPlugins and strategies with several implementations

The examples are complete programs on Spring Framework 7.0 without Spring Boot. Where Spring Boot behaves differently, the text says so.

Constructor injection

Constructor injection passes every required dependency to the constructor, so the object is complete from the moment it exists, and its fields can be final. The example runs the same OrderService twice. The first comes from a Spring context, and the second is built by hand with fakes, the way a unit test would build it:

Java
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

public class ConstructorInjection {

    interface PaymentGateway {
        String charge(String order, int cents);
    }

    interface StockLedger {
        boolean reserve(String order);
    }

    @Component
    static class CardGateway implements PaymentGateway {
        @Override
        public String charge(String order, int cents) {
            return "card charged " + cents + " cents for " + order;
        }
    }

    @Component
    static class WarehouseLedger implements StockLedger {
        @Override
        public boolean reserve(String order) {
            return true;
        }
    }

    @Service
    static class OrderService {
        private final PaymentGateway payments;
        private final StockLedger stock;

        // one constructor: Spring uses it without @Autowired
        OrderService(PaymentGateway payments, StockLedger stock) {
            this.payments = payments;
            this.stock = stock;
        }

        String place(String order, int cents) {
            if (!stock.reserve(order)) {
                return order + " rejected: out of stock";
            }
            return payments.charge(order, cents);
        }
    }

    public static void main(String[] args) {
        System.out.println("With Spring:");
        try (var context = new AnnotationConfigApplicationContext(
                CardGateway.class, WarehouseLedger.class, OrderService.class)) {
            System.out.println("  " + context.getBean(OrderService.class).place("A-1", 2500));
        }

        System.out.println("Without Spring, as a unit test would do it:");
        List<String> charges = new ArrayList<>();
        PaymentGateway fakeGateway = (order, cents) -> {
            charges.add(order);
            return "fake charge for " + order;
        };
        OrderService inStock = new OrderService(fakeGateway, order -> true);
        OrderService soldOut = new OrderService(fakeGateway, order -> false);
        System.out.println("  " + inStock.place("B-1", 900));
        System.out.println("  " + soldOut.place("B-2", 900));
        System.out.println("  charges recorded by the fake: " + charges);
    }
}
Output
With Spring:
  card charged 2500 cents for A-1
Without Spring, as a unit test would do it:
  fake charge for B-1
  B-2 rejected: out of stock
  charges recorded by the fake: [B-1]
  • With Spring, the context found one PaymentGateway bean and one StockLedger bean, called the only constructor with them, and the order was charged 2500 cents. There is no @Autowired anywhere: with a single constructor, Spring uses it automatically.
  • Without Spring, the same class took a lambda as its gateway and another as its ledger. The in-stock order was charged by the fake, the sold-out one was rejected, and the fake recorded only [B-1]. No context, no mocking library and no reflection were needed.

When a class has several constructors, mark the one Spring should use with @Autowired. A constructor with many parameters is a warning sign rather than a problem of the injection style: the class probably does too much. Records work well as beans for the same reason, because their canonical constructor takes every field.

Setter and field injection, and optional dependencies

Setter and field injection set dependencies after the constructor has run. Both work inside a Spring context, but they behave differently once the class is used without one. This program also asks for a bean that does not exist, in three optional ways:

Java
import java.util.Optional;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.stereotype.Component;

public class SetterAndField {

    @Component
    static class AuditLog {
        String record(String event) {
            return "audited: " + event;
        }
    }

    static class SmsSender {   // not registered as a bean in this program
    }

    @Component
    static class FieldInjected {
        @Autowired
        private AuditLog audit;

        String rename(String name) {
            return audit.record("rename to " + name);
        }
    }

    @Component
    static class SetterInjected {
        private AuditLog audit;

        @Autowired
        void setAudit(AuditLog audit) {
            this.audit = audit;
        }

        String rename(String name) {
            return audit.record("rename to " + name);
        }
    }

    @Component
    static class OptionalDependencies {
        @Autowired(required = false)
        void setSms(SmsSender sms) {
            System.out.println("  never called: no SmsSender bean");
        }

        OptionalDependencies(Optional<SmsSender> sms, ObjectProvider<SmsSender> smsProvider) {
            System.out.println("  Optional<SmsSender>           : " + sms);
            System.out.println("  ObjectProvider.getIfAvailable: " + smsProvider.getIfAvailable());
        }
    }

    public static void main(String[] args) {
        System.out.println("Starting the context:");
        try (var context = new AnnotationConfigApplicationContext(AuditLog.class,
                FieldInjected.class, SetterInjected.class, OptionalDependencies.class)) {
            System.out.println("  field  : " + context.getBean(FieldInjected.class).rename("a"));
            System.out.println("  setter : " + context.getBean(SetterInjected.class).rename("b"));
        }

        System.out.println("Created with new, as in a plain unit test:");
        SetterInjected setter = new SetterInjected();
        setter.setAudit(new AuditLog());
        System.out.println("  setter : " + setter.rename("c"));
        try {
            new FieldInjected().rename("d");
        } catch (NullPointerException e) {
            System.out.println("  field  : NullPointerException, the private field is null");
        }
    }
}
Output
Starting the context:
  Optional<SmsSender>           : Optional.empty
  ObjectProvider.getIfAvailable: null
  field  : audited: rename to a
  setter : audited: rename to b
Created with new, as in a plain unit test:
  setter : audited: rename to c
  field  : NullPointerException, the private field is null
  • No SmsSender bean exists. Optional<SmsSender> received Optional.empty, getIfAvailable() returned null, and the @Autowired(required = false) setter was simply not called. Without one of these, the missing bean would have stopped startup.
  • Inside the context, the field-injected and setter-injected beans both worked and printed audited: rename to a and b.
  • Created with new, the setter-injected class could be completed by calling its setter. The field-injected class could not: its private field stayed null and the call threw NullPointerException. A test would need reflection or a Spring context to set it.

Field injection also hides how many dependencies a class has, allows a half-built object, and rules out final fields. It remains common in test classes, where the test framework creates the object. Spring's own documentation recommends constructors for required dependencies and setters for optional ones. A @Nullable parameter, from JSpecify or any annotation named Nullable, also marks a dependency as optional.

When several beans match: @Primary, @Qualifier and @Fallback

Two beans of the same type are common: an email and an SMS notifier, two data sources, a real and a test clock. This program starts four small configurations with two Notifier beans each, and resolves the ambiguity a different way in each:

Java
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.beans.factory.UnsatisfiedDependencyException;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Fallback;
import org.springframework.context.annotation.Primary;

public class Ambiguity {

    record Notifier(String channel) {
    }

    record Alerts(Notifier notifier) {
    }

    @Configuration
    static class TwoBeans {
        @Bean
        Notifier email() {
            return new Notifier("email");
        }

        @Bean
        Notifier sms() {
            return new Notifier("sms");
        }

        @Bean
        Alerts alerts(Notifier notifier) {
            return new Alerts(notifier);
        }
    }

    @Configuration
    static class WithPrimary {
        @Bean
        @Primary
        Notifier email() {
            return new Notifier("email");
        }

        @Bean
        Notifier sms() {
            return new Notifier("sms");
        }

        @Bean
        Alerts alerts(Notifier notifier) {
            return new Alerts(notifier);
        }

        @Bean
        Alerts urgentAlerts(@Qualifier("sms") Notifier notifier) {
            return new Alerts(notifier);
        }
    }

    @Configuration
    static class WithFallback {
        @Bean
        @Fallback
        Notifier logOnly() {
            return new Notifier("log only");
        }

        @Bean
        Notifier slack() {
            return new Notifier("slack");
        }

        @Bean
        Alerts alerts(Notifier notifier) {
            return new Alerts(notifier);
        }
    }

    @Configuration
    static class ByParameterName {
        @Bean
        Notifier email() {
            return new Notifier("email");
        }

        @Bean
        Notifier sms() {
            return new Notifier("sms");
        }

        @Bean
        Alerts alerts(Notifier sms) {   // matches the bean name only with javac -parameters
            return new Alerts(sms);
        }
    }

    static void start(Class<?> config) {
        System.out.println(config.getSimpleName() + ":");
        try (var context = new AnnotationConfigApplicationContext(config)) {
            for (String name : context.getBeanNamesForType(Alerts.class)) {
                System.out.println("  " + name + " uses "
                        + context.getBean(name, Alerts.class).notifier().channel());
            }
        } catch (UnsatisfiedDependencyException e) {
            Throwable cause = e.getMostSpecificCause();
            System.out.println("  failed: " + cause.getClass().getSimpleName());
            if (cause instanceof NoUniqueBeanDefinitionException unique) {
                System.out.println("  found " + unique.getNumberOfBeansFound() + " beans: "
                        + unique.getBeanNamesFound());
            }
        }
    }

    public static void main(String[] args) {
        start(TwoBeans.class);
        start(WithPrimary.class);
        start(WithFallback.class);
        start(ByParameterName.class);
    }
}
Output
TwoBeans:
  failed: NoUniqueBeanDefinitionException
  found 2 beans: [email, sms]
WithPrimary:
  alerts uses email
  urgentAlerts uses sms
WithFallback:
  alerts uses slack
ByParameterName:
  failed: NoUniqueBeanDefinitionException
  found 2 beans: [email, sms]
  • TwoBeans did nothing to help, and startup failed with NoUniqueBeanDefinitionException: found 2 beans: [email, sms]. The exception names every candidate, which tells you where to add a qualifier.
  • In WithPrimary, alerts received the @Primary email notifier, and urgentAlerts received sms because its parameter has @Qualifier("sms"). A qualifier on the injection point wins over @Primary.
  • In WithFallback, the log-only notifier is marked @Fallback, so the only other candidate, slack, was chosen. This suits a default bean in a library that should step aside as soon as the application defines its own.
  • ByParameterName names its parameter sms, which matches a bean name, yet startup failed. Matching by name needs the parameter names in the class file, and this program was compiled without javac -parameters. Compiled with the flag, the same program prints alerts uses sms.

Spring Framework 6.1 stopped reading parameter names from debug information, so name matching depends on -parameters. Spring Boot's Maven parent POM and its Gradle plugin set the flag for you, which is why the same code can work in a Boot build and fail in a plain one. An explicit @Qualifier does not depend on the compiler at all. Spring also logged a warning for each failed startup; those lines are left out of the output here.

Injecting every implementation: lists, maps and generics

Sometimes a class needs all beans of a type, not one: every discount rule, every validator, every event handler. Spring injects them as a List, or as a Map keyed by bean name. It also uses generic type arguments to tell beans apart. Here three discount rules are registered in an order that differs from their @Order values:

Java
import java.util.List;
import java.util.Map;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

public class CollectionInjection {

    interface DiscountRule {
        int percentFor(int cents);
    }

    @Component("loyalty")
    @Order(2)
    static class LoyaltyDiscount implements DiscountRule {
        @Override
        public int percentFor(int cents) {
            return 5;
        }
    }

    @Component("bulk")
    @Order(1)
    static class BulkDiscount implements DiscountRule {
        @Override
        public int percentFor(int cents) {
            return cents >= 10000 ? 10 : 0;
        }
    }

    @Component("seasonal")
    @Order(3)
    static class SeasonalDiscount implements DiscountRule {
        @Override
        public int percentFor(int cents) {
            return 2;
        }
    }

    interface Repository<T> {
        String describe();
    }

    record Customer(String name) {
    }

    record Invoice(int number) {
    }

    @Component
    static class CustomerRepository implements Repository<Customer> {
        @Override
        public String describe() {
            return "CustomerRepository";
        }
    }

    @Component
    static class InvoiceRepository implements Repository<Invoice> {
        @Override
        public String describe() {
            return "InvoiceRepository";
        }
    }

    @Service
    static class Checkout {
        Checkout(List<DiscountRule> rules, Map<String, DiscountRule> byName,
                Repository<Invoice> invoices) {
            System.out.println("List, in @Order order:");
            for (DiscountRule rule : rules) {
                System.out.println("  " + rule.getClass().getSimpleName()
                        + " gives " + rule.percentFor(12000) + "% on 120.00");
            }
            System.out.println("Map keys (bean names): " + byName.keySet());
            System.out.println("Rule picked by name at run time: "
                    + byName.get("seasonal").getClass().getSimpleName());
            System.out.println("Repository<Invoice> resolved to " + invoices.describe());
        }
    }

    public static void main(String[] args) {
        var context = new AnnotationConfigApplicationContext(LoyaltyDiscount.class,
                BulkDiscount.class, SeasonalDiscount.class, CustomerRepository.class,
                InvoiceRepository.class, Checkout.class);
        context.close();
    }
}
Output
List, in @Order order:
  BulkDiscount gives 10% on 120.00
  LoyaltyDiscount gives 5% on 120.00
  SeasonalDiscount gives 2% on 120.00
Map keys (bean names): [loyalty, bulk, seasonal]
Rule picked by name at run time: SeasonalDiscount
Repository<Invoice> resolved to InvoiceRepository
  • The list came in @Order order, bulk (1), loyalty (2), seasonal (3), although the classes were registered as loyalty, bulk, seasonal. Without @Order or the Ordered interface, a list follows registration order.
  • The map's keys are the bean names, [loyalty, bulk, seasonal], in registration order. A map is the usual way to pick a strategy by a name that arrives at run time, as byName.get("seasonal") does.
  • Repository<Invoice> resolved to InvoiceRepository, although CustomerRepository is also a Repository. Spring compares the generic type argument, so generics work as an implicit qualifier.

Adding a new rule is now one new class with @Component: nothing that injects the list has to change. When no bean of the type exists, the two forms differ: a constructor or @Bean method parameter receives an empty list or map, while an @Autowired field or setter fails startup like any missing dependency. ObjectProvider<T> and its orderedStream() handle zero beans the same way everywhere.

Circular dependencies

Two beans that need each other form a cycle. With constructor injection Spring cannot build either one first, so it refuses to start. With field or setter injection it can, in plain Spring, by injecting an early reference to a bean that is not finished yet. This program tries both, then tries the field cycle with circular references turned off, as Spring Boot does:

Java
import org.springframework.beans.factory.UnsatisfiedDependencyException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

public class CircularDependency {

    @Component
    static class OrderService {
        OrderService(CustomerService customers) {
        }
    }

    @Component
    static class CustomerService {
        CustomerService(OrderService orders) {
        }
    }

    @Component
    static class FieldA {
        @Autowired
        FieldB b;
    }

    @Component
    static class FieldB {
        @Autowired
        FieldA a;
    }

    @Component
    public static class LazyOrders {
        private final LazyCustomers customers;

        LazyOrders(@Lazy LazyCustomers customers) {
            this.customers = customers;
        }

        public String customerFor(String order) {
            return customers.name(order);
        }
    }

    @Component
    public static class LazyCustomers {
        private final LazyOrders orders;

        LazyCustomers(LazyOrders orders) {
            this.orders = orders;
        }

        public String name(String order) {
            return "customer of " + order;
        }
    }

    public static void main(String[] args) {
        System.out.println("Constructor cycle:");
        try (var context = new AnnotationConfigApplicationContext(
                OrderService.class, CustomerService.class)) {
            System.out.println("  started: " + context.isActive());
        } catch (UnsatisfiedDependencyException e) {
            Throwable cause = e.getMostSpecificCause();
            System.out.println("  " + cause.getClass().getSimpleName());
            String message = cause.getMessage();
            System.out.println("  " + message.substring(message.indexOf("Requested")));
        }

        System.out.println("Field cycle, circular references allowed (plain Spring default):");
        try (var context = new AnnotationConfigApplicationContext(FieldA.class, FieldB.class)) {
            FieldA a = context.getBean(FieldA.class);
            System.out.println("  started, a.b.a == a: " + (a.b.a == a));
        }

        System.out.println("Field cycle, circular references forbidden (Spring Boot default):");
        var strict = new AnnotationConfigApplicationContext();
        strict.setAllowCircularReferences(false);
        strict.register(FieldA.class, FieldB.class);
        try {
            strict.refresh();
        } catch (UnsatisfiedDependencyException e) {
            System.out.println("  " + e.getMostSpecificCause().getClass().getSimpleName());
        }

        System.out.println("Constructor cycle broken with @Lazy:");
        try (var context = new AnnotationConfigApplicationContext(
                LazyOrders.class, LazyCustomers.class)) {
            LazyOrders orders = context.getBean(LazyOrders.class);
            System.out.println("  injected class: "
                    + orders.customers.getClass().getSimpleName());
            System.out.println("  " + orders.customerFor("A-7"));
        }
    }
}
Output
Constructor cycle:
  BeanCurrentlyInCreationException
  Requested bean is currently in creation: Is there an unresolvable circular reference or an asynchronous initialization dependency?
Field cycle, circular references allowed (plain Spring default):
  started, a.b.a == a: true
Field cycle, circular references forbidden (Spring Boot default):
  BeanCurrentlyInCreationException
Constructor cycle broken with @Lazy:
  injected class: CircularDependency$LazyCustomers$$SpringCGLIB$$0
  customer of A-7
  • The constructor cycle failed with BeanCurrentlyInCreationException. Spring started creating OrderService, needed CustomerService, which needed OrderService again, which was still being created.
  • The field cycle started in plain Spring, and a.b.a == a printed true: each bean holds the other. It works because Spring created FieldA, exposed it early, then created FieldB and gave it the unfinished FieldA.
  • With setAllowCircularReferences(false), the same field cycle failed. Spring Boot has made this the default since 2.6; the property spring.main.allow-circular-references=true turns it back on, but treat that as a stopgap.
  • Marking one constructor parameter @Lazy broke the cycle. Spring injected LazyCustomers$$SpringCGLIB$$0, a proxy that creates or finds the real bean on its first method call, and the call printed customer of A-7.

A cycle is usually a sign that two classes share a responsibility. The lasting fix is to move the shared part into a third bean that both depend on, or to replace one direction with an event. @Lazy and early references hide the cycle; they also mean one bean may be used before it is fully initialized.

Other things to know

  • Injection by type uses the bean's declared type: for a @Bean method, that is the method's return type until the bean is created. Declare the most specific type you want others to inject.
  • Proxied beans: when a bean is wrapped in a JDK interface proxy, it can be injected only through its interface. Plain Spring creates such proxies for beans that implement an interface; Spring Boot uses class-based proxies by default.
  • Static fields: Spring does not inject static fields. A static field marked @Autowired stays null, and Spring logs a message that it is not supported.
  • Configuration values: @Value("${app.timeout}") injects a property instead of a bean, through the same constructor, setter or field mechanisms.
  • Self-injection: a bean can inject itself, with @Lazy, to call its own proxied methods. It is legal but obscure; moving the method to another bean is clearer, as the @Transactional page shows.

Choosing an injection style

Which way to inject which dependency
DependencyUse
Required, known at startupConstructor parameter, final field
OptionalObjectProvider<T>.getIfAvailable(), Optional<T>, or a setter with required = false
Needed only sometimes, or expensive to createObjectProvider<T>, or @Lazy
A new instance per useObjectProvider<T>.getObject() on a prototype bean
One of several beans of the same type@Qualifier at the injection point, or @Primary on the usual one
A library default that the application may replace@Fallback on the default
All implementations of a typeList<T> with @Order, or Map<String, T>
Dependencies in a test classField injection is acceptable there

Constructor injection with final fields covers most beans, keeps classes testable without Spring, and makes cycles fail fast instead of hiding them. The inversion of control page explains the idea behind the container, Spring annotations covers @Component and scanning, and bean scopes shows how prototype and request beans are injected into singletons.