春季战略模式与依赖注入 [英] Strategy Pattern and Dependency Injection in Spring

查看:78
本文介绍了春季战略模式与依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个策略接口,由 StrategyA StrategyB 实现,两者都被定义为 @Component 并且他们也有 @Autowired 属性,如何根据字符串值获取其中一个实例呢?

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?

这是我的Controller的行动,它应该执行策略:

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 ();
}

谢谢!

推荐答案

您可以通过编程方式查找:

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();
}

你可以使用自定义以更高级的方式做到这一点WebArgumentResolver ,但这比它的价值要麻烦得多。

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

这篇关于春季战略模式与依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆