嗨,我在Spring Boot应用程序中有一个策略模式。我所有的策略都有自动装配构造函数。我是Spring靴的新手。我没有最简单的想法,因为自动装配的构造函数已经注入了依赖性,因此我该如何为策略类编写工厂。感谢您为此提供的任何帮助。
注意: 我将省略Intefaces和基类,以免使样本混乱。
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。首先为您的工厂定义一个接口:
public interface MyFactory { Strategy get(String type); } // Could be an abstract class public interface Strategy { void doStuff(); }
然后在您的应用程序中:
@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中,并可以使用以下方法创建:
myFactory.get("beanName");
最好的部分是您可以将Strategy Bean注册为惰性的并具有不同的作用域。