Strategy Pattern and Dependency Dependency in Spring

I have a Strategy interface implemented by StrategyA and StrategyB, both of them are defined as @Component and they also have @Autowired attribute , how can I do to get an instance of one of them based on String value?

This is my Controller action, which should execute the strategy:

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

Thank!

+3
source share
1 answer

You can search programmatically:

private @Autowired BeanFactory beanFactory;

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

You can do it in a more attractive way using a custom one WebArgumentResolver, but this is a lot more of a problem than it costs.

+11
source

Source: https://habr.com/ru/post/1787685/


All Articles