在Spring中实现定制工厂模式
通常,如果我想实现工厂模式,我会这样做在Spring中实现定制工厂模式,spring,factory,Spring,Factory,通常,如果我想实现工厂模式,我会这样做 public class CustomFactory(){ // pay attention: parameter is not a string public MyService getMyService(Object obj){ /* depending on different combinations of fields in an obj the return type will be MyServ
public class CustomFactory(){
// pay attention: parameter is not a string
public MyService getMyService(Object obj){
/* depending on different combinations of fields in an obj the return
type will be MyServiceOne, MyServiceTwo, MyServiceThree
*/
}
}
MyServiceOne、myServiceWO、MyServiceThree是接口MyService的实现
那很好用。
但问题是,我希望用Spring容器实例化我的对象
我看过一些例子,知道如何让Spring容器根据字符串创建对象
问题是:我可以在本例中包括Spring容器对对象的实现吗?或者我应该在其他地方使用Object obj进行所有操作,并在我的CumtomFactory中编写一个方法public MyService getMyService(String String)?那么您认为下面的方法怎么样
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;
}
*/
}
}
编辑:
在评论中回答您的问题:
这和通过字符串获取信息不一样吗 -->是的,当然,你是从春天得到这些豆子的 我的意思是我的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方法中我应该做什么?只需返回新的MyServiceOne()等等
-->请参阅上面代码中的getMyService()方法,它已更新。与按字符串获取不一样吗?我的意思是我的spring.xml应该是什么样子?在getMyService方法中我应该做什么?只需返回新的MyServiceOne()等等?事实上,它成功了!谢谢。我不觉得它很美,不知道为什么,但它起了作用。:)谢谢我很抱歉!我不能很快回复你。这不是为了看起来漂亮,我使用了Spring框架指定的注释方法。