java / beginner
Snippet
Constructor Injection for Loose Coupling
Constructor-based dependency injection in Spring promotes immutability with final fields and ensures that required object dependencies are passed during instantiation without needing field injection.
snippet.java
java
1
2
3
4
5
6
7
8
9
@Servicepublic class OrderService {private final PaymentProcessor paymentProcessor;public OrderService(PaymentProcessor paymentProcessor) {this.paymentProcessor = paymentProcessor;}}
spring
Breakdown
1
@Service
Marks this class as a Spring-managed service bean within the application context.
2
private final PaymentProcessor paymentProcessor;
Declares an immutable dependency reference that cannot be modified after object construction.
3
public OrderService(PaymentProcessor paymentProcessor) {
Defines the single constructor where Spring automatically injects the matching PaymentProcessor bean.
4
this.paymentProcessor = paymentProcessor;
Assigns the injected bean instance to the internal final field.