开发者

Strategy Pattern and Dependency Injection in Spring

开发者 https://www.devze.com 2023-02-06 09:56 出处:网络
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 instanc

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 st开发者_如何学JAVArategyName */;
    strategy.doStuff ();
}

Thanks!


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消