那么,您如何看待以下方式?:
public class CustomFactory {
// Autowire all MyService implementation classes, i.e. MyServiceOne, MyServiceTwo, MyServiceThree
@Autowired
@Qualifier("myServiceBeanOne")
private MyService myServiceOne; // with getter, setter
@Autowired
@Qualifier("myServiceBeanTwo")
private MyService myServiceTwo; // with getter, setter
@Autowired
@Qualifier("myServiceBeanThree")
private MyService myServiceThree; // with getter, setter
public MyService getMyService(){
// return appropriate MyService implementation bean
/*
if(condition_for_myServiceBeanOne) {
return myServiceOne;
}
else if(condition_for_myServiceBeanTwo) {
return myServiceTwo;
} else {
return myServiceThree;
}
*/
}
}
编辑 :
在评论中回答您的问题:
通过String获取不一样吗?
--> 是的,当然,你是从 Spring 中获取这些 bean 的。
我的意思是我的 spring.xml 应该是什么样子?
--> 见下面的 xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- services -->
<bean id="myServiceBeanOne"
class="com.comp.pkg.MyServiceOne">
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<bean id="myServiceBeanTwo"
class="com.comp.pkg.MyServiceTwo">
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<bean id="myServiceBeanThree"
class="com.comp.pkg.MyServiceThree">
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions for services go here -->
</beans>
我应该在 getMyService 方法中做什么?只是返回 new MyServiceOne() 等等还是什么?
--> 参见上面代码中的 getMyService() 方法,它已更新。