通常,如果我想实现工厂模式,我会这样做。
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,MyServiceTwo,MyServiceThree是MyService接口的实现。
这将完美无缺。 但问题是我想让我的对象由Spring容器实现。
我已经查看了一些示例,并且我知道如何使Spring容器根据字符串创建我的对象。
问题是:我可以在这个例子中包含Spring Container对象的实现,还是应该在其他地方使用Object obj进行所有操作,并在CumtomFactory中编写一个方法public MyService getMyService(String string)?
答案 0 :(得分:1)
那你对下面的方式怎么看? :
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.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()等等或什么?
- &GT;请参阅上面代码中的getMyService()方法,它已更新。