Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strategy Pattern and Dependency Injection in Spring

I have an Strategy interface, that is implemented by StrategyA and StrategyB, both of them are defined as @Component's and they have an @Autowired attribute as well, how can I do to obtain an instance of one of them based on an String value?

This is my Controller's action, that should perform the strategy:

@RequestMapping("/blabla")
public void perform (@RequestParam String strategyName) {
    Strategy strategy = (Strategy) /* Get the concrete Strategy based on strategyName */;
    strategy.doStuff ();
}

Thanks!

like image 398
Joaquín L. Robles Avatar asked Dec 13 '22 16:12

Joaquín L. Robles


1 Answers

You can look it up programmatically:

private @Autowired BeanFactory beanFactory;

@RequestMapping("/blabla")
public void perform (@RequestParam String strategyName) {
    Strategy strategy = beanFactory.getBean(strategyName, Strategy.class);
    strategy.doStuff();
}

You could do it a fancier way using a custom WebArgumentResolver, but that's a lot more trouble than it's worth.

like image 129
skaffman Avatar answered Dec 15 '22 06:12

skaffman