0 day streak
java / beginner
Snippet

Constructor Dependency Injection

Constructor injection is the recommended way to handle dependencies in Spring. It ensures the object is always in a valid state and facilitates testing.

snippet.java
java
1
2
3
4
5
6
7
8
@RestController
public class CheckoutController {
private final PaymentProcessor processor;
public CheckoutController(PaymentProcessor processor) {
this.processor = processor;
}
}
spring
Breakdown
1
private final PaymentProcessor processor
The dependency is declared as final, ensuring it cannot be changed after initialization.
2
public CheckoutController(...)
The constructor where Spring automatically injects the required dependency bean.