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
When Spring creates a bean, it looks at each injection point: a constructor parameter, a setter method or a field marked @Autowired
- A
on the injection point, which names the bean to use.@Qualifier - A bean marked
.@Primary - Since Spring Framework 6.2, the one bean left when all the others are marked
.@Fallback - A bean whose name equals the parameter or field name.
If none of these picks a single bean, startup fails with NoUniqueBeanDefinitionException
| Style | How | When injected | Best for |
|---|---|---|---|
| Constructor injection | Constructor parameters; @Autowired | When the object is created | Required dependencies, the default choice |
| Setter injection | @Autowired | After the constructor | Optional dependencies, or ones that may be replaced |
| Field injection | @Autowired | After the constructor | Test classes; avoid in production code |
ObjectProvider<T> | Inject the provider, call getObject()getIfAvailable() | When you call it | Optional, lazy or prototype dependencies |
| Collections and maps | List<T>Map<String, T> | When the object is created | Plugins 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 finalOrderService
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);
}
}
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
bean and onePaymentGateway bean, called the only constructor with them, and the order was chargedStockLedger . There is no2500 cents anywhere: with a single constructor, Spring uses it automatically.@Autowired - 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
. No context, no mocking library and no reflection were needed.[B-1]
When a class has several constructors, mark the one Spring should use with @Autowired
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:
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");
}
}
}
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
bean exists.SmsSender receivedOptional<SmsSender> ,Optional.empty returnedgetIfAvailable() , and thenull setter was simply not called. Without one of these, the missing bean would have stopped startup.@Autowired(required = false) - Inside the context, the field-injected and setter-injected beans both worked and printed
andaudited: rename to a .b - Created with
, the setter-injected class could be completed by calling its setter. The field-injected class could not: itsnew field stayedprivate and the call threwnull . A test would need reflection or a Spring context to set it.NullPointerException
Field injection also hides how many dependencies a class has, allows a half-built object, and rules out final@NullableNullable
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
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);
}
}
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]
did nothing to help, and startup failed withTwoBeans :NoUniqueBeanDefinitionException . The exception names every candidate, which tells you where to add a qualifier.found 2 beans: [email, sms]- In
,WithPrimary received thealerts email notifier, and@Primary receivedurgentAlerts because its parameter hassms . A qualifier on the injection point wins over@Qualifier("sms") .@Primary - In
, the log-only notifier is markedWithFallback , so the only other candidate,@Fallback , was chosen. This suits a default bean in a library that should step aside as soon as the application defines its own.slack names its parameterByParameterName , which matches a bean name, yet startup failed. Matching by name needs the parameter names in the class file, and this program was compiled withoutsms . Compiled with the flag, the same program printsjavac -parameters .alerts uses sms
Spring Framework 6.1 stopped reading parameter names from debug information, so name matching depends on -parameters@Qualifier
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 ListMap@Order
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();
}
}
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, bulk (1), loyalty (2), seasonal (3), although the classes were registered as loyalty, bulk, seasonal. Without@Order or the@Order interface, a list follows registration order.Ordered - The map's keys are the bean names,
, in registration order. A map is the usual way to pick a strategy by a name that arrives at run time, as[loyalty, bulk, seasonal] does.byName.get("seasonal") resolved toRepository<Invoice> , althoughInvoiceRepository is also aCustomerRepository . Spring compares the generic type argument, so generics work as an implicit qualifier.Repository
Adding a new rule is now one new class with @Component@Bean@AutowiredObjectProvider<T>orderedStream()
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:
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"));
}
}
}
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
. Spring started creatingBeanCurrentlyInCreationException , neededOrderService , which neededCustomerService again, which was still being created.OrderService - The field cycle started in plain Spring, and
printeda.b.a == a : each bean holds the other. It works because Spring createdtrue , exposed it early, then createdFieldA and gave it the unfinishedFieldB .FieldA - With
, the same field cycle failed. Spring Boot has made this the default since 2.6; the propertysetAllowCircularReferences(false) turns it back on, but treat that as a stopgap.spring.main.allow-circular-references=true - Marking one constructor parameter
broke the cycle. Spring injected@Lazy , a proxy that creates or finds the real bean on its first method call, and the call printedLazyCustomers$$SpringCGLIB$$0 .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
Other things to know
- Injection by type uses the bean's declared type: for a
method, that is the method's return type until the bean is created. Declare the most specific type you want others to inject.@Bean - 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
stays@Autowired , and Spring logs a message that it is not supported.null - Configuration values:
injects a property instead of a bean, through the same constructor, setter or field mechanisms.@Value("${app.timeout}") - Self-injection: a bean can inject itself, with
, to call its own proxied methods. It is legal but obscure; moving the method to another bean is clearer, as the@Lazy@Transactional page shows.
Choosing an injection style
| Dependency | Use |
|---|---|
| Required, known at startup | Constructor parameter, final |
| Optional | ObjectProvider<T>.getIfAvailable()Optional<T>required = false |
| Needed only sometimes, or expensive to create | ObjectProvider<T>@Lazy |
| A new instance per use | ObjectProvider<T>.getObject() |
| One of several beans of the same type | @Qualifier@Primary |
| A library default that the application may replace | @Fallback |
| All implementations of a type | List<T>@OrderMap<String, T> |
| Dependencies in a test class | Field injection is acceptable there |
Constructor injection with final@Component