Spring: Constructor injection is preferred over field injection

A constructor makes dependencies explicit, allows final fields, and lets the object be built in a test without a container.

Code
@Service
public class OrderService {

    private final OrderRepository orders;
    private final PaymentGateway payments;

    // No @Autowired needed: one constructor means Spring uses it.
    public OrderService(OrderRepository orders, PaymentGateway payments) {
        this.orders = orders;
        this.payments = payments;
    }
}

// In a test, no Spring at all:
var service = new OrderService(new FakeOrderRepository(), new FakePaymentGateway());
Output
Both fields are final and can never be null.
A missing dependency fails at startup, not at the first request.
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-11