简体   繁体   English

春季战略模式与依赖注入

[英]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? 我有一个Strategy接口,由StrategyAStrategyB实现,它们都被定义为@Component ,它们也有@Autowired属性,如何根据String获取其中一个的实例值?

This is my Controller's action, that should perform the strategy: 这是我的Controller的动作,它应该执行策略:

@RequestMapping("/blabla")
public void perform (@RequestParam String strategyName) {
    Strategy strategy = (Strategy) /* Get the concrete Strategy based on strategyName */;
    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. 你可以使用自定义的WebArgumentResolver以更好的方式做到这WebArgumentResolver ,但这比它的价值更麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM