IoC and dependency injection · Topic 3 of 7
Constructor injection
Definition​
Constructor injection means a class lists what it needs as constructor parameters and Spring supplies them. It is the preferred style: the dependencies are visible, they can be final, and the class is easy to create in a plain unit test.
Example code​
A service that receives its dependency through the constructor
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
@Component
class PriceRepository {
int priceOf(String item) { return item.length() * 10; }
}
@Service
class OrderService {
private final PriceRepository prices; // final: it can never be missing or changed
OrderService(PriceRepository prices) { // Spring passes the bean in
this.prices = prices;
}
int total(String... items) {
int sum = 0;
for (String item : items) sum += prices.priceOf(item);
return sum;
}
}
@ComponentScan
class Demo {
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Demo.class)) {
System.out.println(context.getBean(OrderService.class).total("pen", "book"));
}
// in a unit test you can skip Spring: new OrderService(new PriceRepository())
}
}
// Output:
// 70
Finished this page? Track your progress (saved only in your browser).