Skip to main content
PreparationZone Logo
PrepZone

Constructor, Setter, and Field Injection

Three ways to inject dependencies — and why constructor injection is the default choice.

Pass checkpoint below

Why this matters

  • Constructor injection is the Spring team's recommended style — it makes BookStore services testable and immutable.
  • Field injection looks shorter but hides dependencies and breaks unit tests that do not boot the full context.
  • Interviewers ask you to compare the three styles; knowing the trade-offs signals production experience.

Constructor injection (preferred)

L1 · Fresher

Dependencies are final fields set once at construction — immutable and test-friendly. BookStore services should expose one obvious constructor for Spring to call.

Setter and field injection

L2 · Intermediate

Setter injection allows optional dependencies; field injection hides requirements and complicates unit tests without Spring. Interviewers expect you to defend constructor injection.

@Qualifier and @Primary

L3 · Advanced

Multiple PaymentClient beans need @Qualifier("stripe") or a @Primary default. Without them, NoUniqueBeanDefinitionException stops startup.

Injection vs lookup

L4 · Expert

ObjectProvider<T> and ApplicationContext.getBean defer or optionally resolve beans — useful for prototypes, plugins, or framework code. Avoid lookup in domain services when injection suffices.

Constructor injection (preferred)

Java
// learn:fragment
@Service
public class BookService {
    private final BookRepository repository;
    private final PricingClient pricingClient;

    public BookService(BookRepository repository, PricingClient pricingClient) {
        this.repository = repository;
        this.pricingClient = pricingClient;
    }

    public Book findById(Long id) {
        return repository.findById(id)
            .orElseThrow(() -> new BookNotFoundException(id));
    }
}

With a single constructor, @Autowired is optional since Spring 4.3. Fields are final, dependencies are explicit, and the object is fully initialised after construction.

Setter injection

Java
// learn:fragment
@Service
public class BookService {
    private BookRepository repository;

    @Autowired
    public void setRepository(BookRepository repository) {
        this.repository = repository;
    }
}

Setters allow changing dependencies after construction — useful for optional dependencies but rare in modern Boot apps. The object is in a partially initialised state between construction and setter call.

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Still to come · 6 sections

  • Field injection (avoid)
  • Testing with constructor injection
  • Optional dependencies
  • Multiple implementations
  • Injection in non-Spring classes
  • Lombok shortcut

Test yourself

Answer these before moving on — recall is what makes it stick.