IoC and dependency injection · Topic 5 of 7
Injecting all implementations
Definition​
Spring can inject every bean of a type at once, as a List or a Map keyed by bean name. That lets you add a new implementation without changing the code that uses them, for example a new payment method.
Example code​
A list and a map of all discount rules
import java.util.List;
import java.util.Map;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
interface DiscountRule { int apply(int price); }
@Component("student")
class StudentRule implements DiscountRule { public int apply(int price) { return price - 10; } }
@Component("festival")
class FestivalRule implements DiscountRule { public int apply(int price) { return price - 5; } }
@Component
class PriceCalculator {
private final List<DiscountRule> rules;
private final Map<String, DiscountRule> byName;
PriceCalculator(List<DiscountRule> rules, Map<String, DiscountRule> byName) { // every implementation
this.rules = rules;
this.byName = byName;
}
int afterAll(int price) {
for (DiscountRule rule : rules) price = rule.apply(price);
return price;
}
int afterOne(String name, int price) { return byName.get(name).apply(price); }
}
@ComponentScan
class Demo {
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Demo.class)) {
PriceCalculator calculator = context.getBean(PriceCalculator.class);
System.out.println(calculator.afterAll(100)); // both rules applied
System.out.println(calculator.afterOne("student", 100)); // one rule picked by bean name
}
}
}
// Output:
// 85
// 90
Finished this page? Track your progress (saved only in your browser).