Constructor injection
On This Lesson 4 topics
This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.
In this lesson
use constructor injection and say why it beats field injection.
Planned topics
- Spring passes beans into the constructor. With one constructor,
@Autowiredis not needed. - Fields can be
final: the object is complete and never half-built. - Dependencies are visible in the signature; tests just call
new. - Field injection (
@Autowiredon a field) hides dependencies, needs reflection in tests, and preventsfinal.
Draft outline details
Demonstration
@Service
public class OrderService {
private final PaymentProvider payment;
public OrderService(PaymentProvider payment) { this.payment = payment; }
}Check your understanding
Why can a constructor-injected field be final?
Show answer
It is set once, in the constructor.
Practice
Apply this lesson with the module's lab, exercises and quiz.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.