对于不同输入需要调用不同实现类,可以考虑使用ServiceLocatorFactoryBean
定义一个interface代理接口(根据类型来判断选择哪一个实现)
public interface BeanFactory {
//type 是具体Bean类型
TestBeanFactory get(String type);
}
定义ServiceLocatorFactoryBean定位配置类
@Configuration
public class TestFactoryConfig {
@Bean("Test")
public ServiceLocatorFactoryBean dataWarehouseFactory() {
ServiceLocatorFactoryBean dataWarehouseFactory = new ServiceLocatorFactoryBean();
dataWarehouseFactory.setServiceLocatorInterface(BeanFactory.class);
return dataWarehouseFactory;
}
定义定义一个interface接口
public interface TestBeanFactory {
String geName();
}
编写TestFactoryService的实现类,根据方法getBean获取具体的Bean方法
@Service("A")
public class TestBeanFactoryImplA implements TestBeanFactory {
@Override
public String getName() {
return "调用A成功";
}
}
@Service("B")
public class TestBeanFactoryImplB implements TestBeanFactory {
@Override
public String getName() {
return "调用B成功";
}
}
测试1:
@Resource
private BeanFactory beanFactory;
@Test
public void DemoTest() {
TestBeanFactory testBeanFactory = beanFactory.get("B");
System.out.println("输出结果:"+testBeanFactory.getName());
}
输出:输出结果:调用B成功
测试2:
@Resource
private BeanFactory beanFactory;
@Test
public void DemoTest() {
TestBeanFactory testBeanFactory = beanFactory.get("A");
System.out.println("输出结果:"+testBeanFactory.getName());
}
输出:输出结果:调用A成功
标签:String,TestBeanFactory,getName,BeanFactory,ServiceLocatorFactoryBean,获取,Bean,pub From: https://blog.51cto.com/u_16226278/7086483