java / beginner
Snippet
Implementing Inversion of Control with Constructor Injection
Constructor injection adheres to the Inversion of Control pattern by supplying required dependencies externally when the class is instantiated.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
@Servicepublic class OrderService {private final PaymentGateway paymentGateway;public OrderService(PaymentGateway paymentGateway) {this.paymentGateway = paymentGateway;}public boolean processOrder(double amount) {return this.paymentGateway.charge(amount);}}
spring
Breakdown
1
private final PaymentGateway paymentGateway;
Declares an immutable dependency field that must be initialized upon construction.
2
public OrderService(PaymentGateway paymentGateway) {
Receives the dependency directly via constructor parameters, enabling Spring to inject the bean.
3
return this.paymentGateway.charge(amount);
Delegates the billing operation to the injected PaymentGateway instance.