Constructor injection and why to prefer it
45 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Every service needs helpers, such as a stock checker or a notifier. How the class receives them decides whether it is easy to test, and whether a mistake shows up at startup or in front of a customer.
One constructor, final fields, no @Autowired
Constructor injection means a class lists its dependencies as constructor parameters, and Spring passes the matching beans in when it creates the object. With exactly one constructor, @Autowired is not needed.
OrderService needs a StockChecker and a Notifier. It lists both as constructor parameters and stores them in private final fields. The second example shows what a second constructor breaks.
Example 1 · Notifier.java, SmsNotifier.java, StockChecker.java, OrderService.java, OrderRunner.java
Runs in: the di-lab practice project (Spring Boot 4.1)
package com.shoplite.lab;
public interface Notifier { void send(String phone, String text);}
package com.shoplite.lab;
import org.springframework.stereotype.Component;
@Componentpublic class SmsNotifier implements Notifier {
@Override public void send(String phone, String text) { System.out.println("SMS to " + phone + ": " + text); }}
package com.shoplite.lab;
import java.util.Map;
import org.springframework.stereotype.Component;
@Componentpublic class StockChecker {
private final Map<String, Integer> stockBySku = Map.of("BOOK-101", 5, "PEN-007", 0);
public boolean inStock(String sku, int quantity) { return stockBySku.getOrDefault(sku, 0) >= quantity; }}
package com.shoplite.lab;
import org.springframework.stereotype.Service;
@Servicepublic class OrderService {
private final StockChecker stockChecker; private final Notifier notifier;
public OrderService(StockChecker stockChecker, Notifier notifier) { // no @Autowired needed this.stockChecker = stockChecker; this.notifier = notifier; }
public String placeOrder(String phone, String sku, int quantity) { if (!stockChecker.inStock(sku, quantity)) { return "Rejected: " + sku + " is out of stock"; } notifier.send(phone, "Order placed for " + quantity + " x " + sku); return "Placed: " + quantity + " x " + sku; }}
package com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class OrderRunner implements CommandLineRunner {
private final OrderService orderService;
public OrderRunner(OrderService orderService) { this.orderService = orderService; }
@Override public void run(String... args) { System.out.println(orderService.placeOrder("9845012345", "BOOK-101", 2)); System.out.println(orderService.placeOrder("9845012345", "PEN-007", 1)); }}SMS to 9845012345: Order placed for 2 x BOOK-101 Placed: 2 x BOOK-101 Rejected: PEN-007 is out of stock
What this code does
OrderServicehas one constructor, so Spring uses it: it finds theStockCheckerbean and the only bean that implementsNotifier(SmsNotifier) and passes both in.- The constructor asks for the interface
Notifier, notSmsNotifier.OrderServicedoes not care how messages are sent, which makes a fake easy to pass in later. - Both fields are
final: once the service exists, its helpers cannot be swapped or set tonullby any caller.
Example 2 · src/main/java/com/shoplite/lab/OrderService.java
Runs in: the di-lab practice project (Spring Boot 4.1)
package com.shoplite.lab;
import org.springframework.stereotype.Service;
@Servicepublic class OrderService {
private final StockChecker stockChecker; private final Notifier notifier;
public OrderService(StockChecker stockChecker, Notifier notifier) { this.stockChecker = stockChecker; this.notifier = notifier; }
public OrderService(StockChecker stockChecker) { // "handy for tests": sends no SMS this(stockChecker, (phone, text) -> { }); }
public String placeOrder(String phone, String sku, int quantity) { if (!stockChecker.inStock(sku, quantity)) { return "Rejected: " + sku + " is out of stock"; } notifier.send(phone, "Order placed for " + quantity + " x " + sku); return "Placed: " + quantity + " x " + sku; }}2026-10-16T10:13:46.158+05:30 ERROR 16556 --- [di-lab] [ main] o.s.boot.SpringApplication : Application run failed
...
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.shoplite.lab.OrderService]: No default constructor found
...
Caused by: java.lang.NoSuchMethodException: com.shoplite.lab.OrderService.<init>()What this code does
- A second constructor was added "for tests". With two constructors and no
@Autowired, Spring looks for a no-argument constructor, finds none and fails. - Read the last
Caused bylines:No default constructor foundandOrderService.<init>(), the no-argument constructor. - Fix: put
@Autowired(fromorg.springframework.beans.factory.annotation) on the two-parameter constructor. The app then prints the same lines as Example 1. Simpler still: delete the extra constructor, because a test can pass a fake to the main one.
Spring reads the parameter types, finds a bean for each one and calls the constructor. The final fields are set once, in the constructor, and can never change or stay null: the object is complete the moment it exists, which matters because one singleton bean is shared by every caller.
Give the class a second constructor and Spring no longer knows which one to call. Spring looks for a no-argument constructor, finds none, and startup fails with No default constructor found. Mark the one Spring should use with @Autowired, or better, keep a single constructor.
Field and setter injection, and why ShopLite avoids field injection
Field injection puts @Autowired on a field: Spring creates the object with the no-argument constructor and then fills the field. Setter injection does the same through a setter method.
FieldOrderService puts @Autowired on its fields. Inside Spring it works, but a plain new gives an object whose fields are null.
Example 3 · FieldOrderService.java, FieldInjectionRunner.java
Runs in: the di-lab practice project (Spring Boot 4.1)
package com.shoplite.lab;
import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;
@Servicepublic class FieldOrderService {
@Autowired private StockChecker stockChecker; // field injection: Spring sets it after creating the object
@Autowired private Notifier notifier;
public String placeOrder(String phone, String sku, int quantity) { if (!stockChecker.inStock(sku, quantity)) { return "Rejected: " + sku + " is out of stock"; } notifier.send(phone, "Order placed for " + quantity + " x " + sku); return "Placed: " + quantity + " x " + sku; }}
package com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class FieldInjectionRunner implements CommandLineRunner {
private final FieldOrderService fromSpring;
public FieldInjectionRunner(FieldOrderService fromSpring) { this.fromSpring = fromSpring; }
@Override public void run(String... args) { System.out.println("From Spring: " + fromSpring.placeOrder("9845012345", "BOOK-101", 1));
FieldOrderService byHand = new FieldOrderService(); // what a unit test would do try { System.out.println("By hand: " + byHand.placeOrder("9845012345", "BOOK-101", 1)); } catch (NullPointerException e) { System.out.println("By hand: NullPointerException"); System.out.println(" " + e.getMessage()); } }}SMS to 9845012345: Order placed for 1 x BOOK-101 From Spring: Placed: 1 x BOOK-101 By hand: NullPointerException Cannot invoke "com.shoplite.lab.StockChecker.inStock(String, int)" because "this.stockChecker" is null
What this code does
- Inside Spring, field injection works: the bean from Spring has both fields filled and places the order.
new FieldOrderService()compiles fine, because the class pretends to need nothing. Its fields arenull, and the first call fails with aNullPointerExceptionthat namesthis.stockChecker.- With constructor injection,
new OrderService()would not even compile. The mistake is caught by the compiler, not at run time.
Both work inside Spring, but the class looks as if it needs nothing. Anyone who creates it with new, such as a unit test, gets null fields and a NullPointerException at the first call. The fields cannot be final, and a class can quietly collect ten hidden dependencies.
ShopLite uses constructor injection everywhere. Setter injection is acceptable only for a truly optional dependency with a sensible default, and the Qualifier and Primary lesson shows a cleaner tool for that.
Find the bug
Find the injection bug
Each class should be safe to create with new. Tap the wrong line.
A test calls new OrderService() and gets a NullPointerException.
Round 1 of 2Unit testing an injected class with plain new
A fake is a small class written for a test that replaces a real dependency. It behaves in a fixed way and records what happened, such as a Notifier that stores messages in a list instead of sending SMS.
OrderServiceTest builds OrderService with new, a real StockChecker and a fake Notifier that records messages. No Spring context starts.
Example 4 · src/test/java/com/shoplite/lab/OrderServiceTest.java
Runs in: the di-lab practice project (Spring Boot 4.1)
package com.shoplite.lab;
import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;import java.util.List;
import org.junit.jupiter.api.Test;
class OrderServiceTest {
private final RecordingNotifier notifier = new RecordingNotifier(); private final OrderService service = new OrderService(new StockChecker(), notifier);
@Test void placesOrderAndSendsOneSms() { String result = service.placeOrder("9845012345", "BOOK-101", 2);
assertEquals("Placed: 2 x BOOK-101", result); assertEquals(List.of("9845012345: Order placed for 2 x BOOK-101"), notifier.sent); }
@Test void rejectsOrderWhenOutOfStockAndSendsNothing() { String result = service.placeOrder("9845012345", "PEN-007", 1);
assertEquals("Rejected: PEN-007 is out of stock", result); assertTrue(notifier.sent.isEmpty()); }}
// A fake Notifier: it records messages instead of sending real SMSclass RecordingNotifier implements Notifier {
final List<String> sent = new ArrayList<>();
@Override public void send(String phone, String text) { sent.add(phone + ": " + text); }}[INFO] T E S T S
...
[INFO] Running com.shoplite.lab.OrderServiceTest
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.145 s -- in com.shoplite.lab.OrderServiceTest
...
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
...
[INFO] BUILD SUCCESSWhat this code does
- The test builds
OrderServicewithnew, a realStockCheckerand aRecordingNotifierfake. No Spring context starts. - The first test checks the result and that exactly one message was "sent". The second checks that an out-of-stock order sends nothing, which you could never check with real SMS.
- Run it with
./mvnw test(Windows:mvnw test) or the IDE's run button. The test methods take well under a second; most of the time is Maven itself.
A unit test checks one class on its own. Because the dependencies come in through the constructor, the test passes whatever it wants and then checks the list of recorded messages. No Spring context starts, so the test runs in milliseconds and cannot send a message to a real phone.
With field injection you would need to start Spring, or use reflection to set private fields, just to test one method.
Circular dependencies: fix the design, not the error
A circular dependency is a loop of beans that need each other, such as OrderService needing InvoiceService while InvoiceService needs OrderService. Spring cannot build either one first, so startup stops.
OrderService and InvoiceService each take the other in their constructor. Start the app and read the report, then break the loop with a third class.
Example 5 · OrderService.java, InvoiceService.java
Runs in: the di-lab practice project (Spring Boot 4.1)
package com.shoplite.lab;
import java.math.BigDecimal;
import org.springframework.stereotype.Service;
@Servicepublic class OrderService {
private final InvoiceService invoiceService;
public OrderService(InvoiceService invoiceService) { this.invoiceService = invoiceService; }
public BigDecimal orderTotal(String orderId) { return new BigDecimal("1798.00"); // pretend: sum of the order's items }
public String placeOrder(String orderId) { return invoiceService.createInvoice(orderId); }}
package com.shoplite.lab;
import org.springframework.stereotype.Service;
@Servicepublic class InvoiceService {
private final OrderService orderService;
public InvoiceService(OrderService orderService) { this.orderService = orderService; }
public String createInvoice(String orderId) { return "Invoice for " + orderId + ": Rs " + orderService.orderTotal(orderId); }}2026-10-16T10:14:33.507+05:30 ERROR 10848 --- [di-lab] [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: The dependencies of some of the beans in the application context form a cycle: ┌─────┐ | invoiceService defined in file [C:\work\di-lab\target\classes\com\shoplite\lab\InvoiceService.class] ↑ ↓ | orderService defined in file [C:\work\di-lab\target\classes\com\shoplite\lab\OrderService.class] └─────┘ Action: Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.
What this code does
OrderServiceneedsInvoiceServiceto create invoices, andInvoiceServiceneedsOrderServicefor the total. Neither can be built first, so Spring stops before any runner runs.- The box shows the loop:
invoiceService→orderService→ back toinvoiceService. Your file paths will differ.
Example 6 · OrderTotalCalculator.java, InvoiceService.java, OrderService.java, InvoiceRunner.java
Runs in: the di-lab practice project (Spring Boot 4.1)
package com.shoplite.lab;
import java.math.BigDecimal;
import org.springframework.stereotype.Component;
@Componentpublic class OrderTotalCalculator {
public BigDecimal orderTotal(String orderId) { return new BigDecimal("1798.00"); // pretend: sum of the order's items }}
package com.shoplite.lab;
import org.springframework.stereotype.Service;
@Servicepublic class InvoiceService {
private final OrderTotalCalculator totals;
public InvoiceService(OrderTotalCalculator totals) { this.totals = totals; }
public String createInvoice(String orderId) { return "Invoice for " + orderId + ": Rs " + totals.orderTotal(orderId); }}
package com.shoplite.lab;
import org.springframework.stereotype.Service;
@Servicepublic class OrderService {
private final InvoiceService invoiceService;
public OrderService(InvoiceService invoiceService) { this.invoiceService = invoiceService; }
public String placeOrder(String orderId) { return invoiceService.createInvoice(orderId); }}
package com.shoplite.lab;
import org.springframework.boot.CommandLineRunner;import org.springframework.stereotype.Component;
@Componentpublic class InvoiceRunner implements CommandLineRunner {
private final OrderService orderService;
public InvoiceRunner(OrderService orderService) { this.orderService = orderService; }
@Override public void run(String... args) { System.out.println(orderService.placeOrder("ORD-17")); }}Invoice for ORD-17: Rs 1798.00
What this code does
- The shared logic, working out an order total, moves into
OrderTotalCalculator.InvoiceServicenow depends on the calculator, not onOrderService. - The dependencies form a line,
OrderService→InvoiceService→OrderTotalCalculator, so Spring builds them from right to left and the app starts.
The report draws the loop as a small box. Since Spring Boot 2.6 such cycles are forbidden by default. The report even mentions spring.main.allow-circular-references=true, but that only works with field or setter injection and hides a design problem.
The real fix is a redesign. Usually both classes share a small piece of logic. Move it into a third class that both depend on, and the loop becomes a line: OrderService → InvoiceService → OrderTotalCalculator.
Too many constructor parameters: the class does too much
This CheckoutService asks for nine dependencies. Count them.
@Servicepublic class CheckoutService {
public CheckoutService(StockChecker stock, PaymentGateway payments, CouponBook coupons, FestivalCalendar festivals, TaxCalculator tax, DeliveryFees delivery, InvoicePrinter invoices, Notifier notifier, LoyaltyPoints points) { // 9 dependencies: too many jobs ... }}A constructor with seven or more parameters is a warning sign: the class has too many jobs, so it needs too many helpers. Constructor injection makes the problem visible; with field injection the same class would look harmless.
Group the dependencies by job. Coupons, tax and delivery fees all answer one question, "what is the final price?", so they belong in a PricingService, and CheckoutService then needs four helpers instead of nine. There is no fixed limit: ask whether you can describe the class in one sentence without "and", and if not, split it.
Next step
Check your understanding
11 quick questions