SPRING CONCEPTS

Constructor, setter and field injection

Spring Concepts / Constructor, setter and field injection

Injection describes how an object receives another object it needs.

Understand the idea

Registration makes a bean available in the container; injection supplies its reference to another object. In Stage 16, Spring wires the ordinary singleton beans at startup, not compilation. ProductService is a required constructor dependency. If no Notifier bean exists, required=false makes Spring skip the setter and preserve the existing field value (null here). The report handles that absence safely. A checkbox controls use during a request, not bean availability. Optional<T> can express an optional constructor dependency too. Field injection hides dependencies from ordinary construction; a final reference does not make the referenced object immutable.

A concrete example

new ProductService(fakeRepository)

In the application

See the independently runnable examples in Stage 15, Stage 16.

Prefer required constructor arguments; mark a setter optional deliberately rather than assuming all setters are optional.

Optional dependency or optional action?

An optional dependency may be absent when Spring prepares the receiving bean. A checkbox only decides whether to use functionality for one request. If the helper is always available, its injection can remain required even when its use is conditional.

Registration makes a bean available in the container. Injection supplies its reference to another object. Optional injection does not register, disable or remove a bean. In the Stage 16 singleton example, configuration and wiring occur at application startup, not Java compilation.

What required=false actually does

If no matching bean exists, Spring skips a non-required setter or field injection. The existing value remains; it is null in Stage 16 because no initial helper was assigned. ReportService.message() deliberately handles that absence.

Optional<T> is another approach, including for constructor parameters: Spring supplies Optional.empty() for an absent helper. Optional injection does not hide bean-creation failures or resolve ambiguous candidates.

Meet the Stage 16 classes

ReportService is our new Java class, not a Spring keyword. It obtains the count from ProductService and optional display text from Notifier. Notifier only returns the banner text; it sends no email.

Bean-registration conditions such as profiles or Boot property conditions answer whether the helper should exist. The receiving object must separately decide whether it can work without the helper.

See it in a working stage

Related concepts

Read the official documentation ↗
Java 21 · Spring Boot 4.1.1 · Edupoly