java / intermediate
Snippet
Resolving Runtime Workflow Strategies via Map Injection
Spring automatically populates map dependencies where the key matches the component bean name and the value is the bean instance. This mechanism eliminates complex conditional branching by delegating execution directly to the resolved bean at runtime.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Servicepublic class PaymentRoutingService {private final Map<String, PaymentProcessor> processors;public PaymentRoutingService(Map<String, PaymentProcessor> processors) {this.processors = processors;}public void executePayment(String provider, BigDecimal amount) {PaymentProcessor processor = processors.get(provider.toLowerCase() + "Processor");if (processor == null) {throw new IllegalArgumentException("Unknown provider: " + provider);}processor.process(amount);}}
spring
Breakdown
1
private final Map<String, PaymentProcessor> processors;
Collects all beans implementing PaymentProcessor mapped by their spring bean names.
2
public PaymentRoutingService(Map<String, PaymentProcessor> processors)
Uses constructor injection to populate the strategy map at startup.
3
processor.process(amount);
Dispatches execution to the dynamically selected processor instance.