Spring Boot中的策略 [英] Strategy within Spring boot
问题描述
我在Spring Boot应用程序中有一个策略模式.我所有的策略都有自动装配构造函数.我是春季靴的新手.我没有最简单的想法,因为自动装配的构造函数已经注入了依赖性,因此我该如何为策略类编写工厂.感谢您为此提供的帮助.
Hi I have a strategy pattern in a spring boot application. All my strategies have autowired constructors. I am new to spring boot. I do not have a simplest of idea how am I going to write my factory for strategy classes as autowired constructors have injected dependencies. I appreciate any help I get with this.
注意::我省略了Intefaces和基类,以免使样本混乱.
NOTE: I am leaving out out Intefaces and base classes to not to clutter sample.
public class StrategyA implement Strategy {
private DependencyA depA;
private DependencyB depB;
@Autowired
public StragegyA(DependencyA depA, DependencyB depB) {
this.depA = depA;
this.depB = depB;
}
}
public class StrategyB implements Strategy {
private DependencyA depA;
private DependencyB depB;
@Autowired
public StragegyB(DependencyA depA, DependencyB depB) {
this.depA = depA;
this.depB = depB;
}
}
public class StrategyFactory {
public Strategy getStrategy(String strategyName) {
if (name.equals("StrategyA")) {
<b>return StrategyA; //My problem is here
} else {
return StrategyB; // And Here
}
}
}
推荐答案
所有先前的答案都使用spring DI的直接用法.但是,也可以使用ServiceLocatorFactoryBean来创建工厂,而不必在工厂中指定任何bean. 首先为您的工厂定义一个接口:
All the previous answers are using a pretty straight forward usage of spring DI. However it's also possible to use ServiceLocatorFactoryBean in order to create a factory without having to specify any bean in the factory. First define a interface for your factory:
public interface MyFactory {
Strategy get(String type);
}
// Could be an abstract class
public interface Strategy {
void doStuff();
}
然后在您的应用程序中:
Then in your application:
@Configuration
public class AppConfiguration {
@Autowired
private BeanFactory beanFactory;
public ServiceLocatorFactoryBean myFactoryLocator() {
final ServiceLocatorFactoryBean locator = new ServiceLocatorFactoryBean();
locator.setServiceLocatorInterface(MyFactory.class);
locator.setBeanFactory(beanFactory);
return locator;
}
@Bean
public MyFactory myFactory() {
final ServiceLocatorFactoryBean locator = myFactoryLocator();
locator.afterPropertiesSet();
return (MyFactory) locator.getObject();
}
}
现在,您可以定义实现/扩展的bean(使用批注@ Service,@ Component或@Bean),它们会自动注册到MyFactory bean中,并可以使用以下方法创建:
Now you can define bean (using annotation @Service, @Component or @Bean) that implements/extends and they are automatically registered into the MyFactory bean and can be created with:
myFactory.get("beanName");
最好的部分是您可以将Strategy Bean注册为惰性的并具有不同的作用域.
The best part is you can register the Strategy bean as lazy and with different scopes.
这篇关于Spring Boot中的策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!