2
我是新來的春天。彈簧依賴注入工廠(動態值)
我有一個rulefactory,這將基於該類型值
一個靜態方法 返回實例現在我得到的主要方法,參數的類型。
現在我想將參數類型傳遞給工廠方法getInstance 類型參數。
該怎麼做。
/*工廠類getInstance將返回RuleEvaluation的子類型,爲了簡單起見,我沒有 提供SingleRuleEvaluation和MassRuleEvaluation的Implementation類。基本上這兩個類實現RuleEvaluation */
public class RuleEvalFactory {
public static RuleEvaluation getInstance(String type) {
if (type != null && type.equals("Single")) {
return new SingleRuleEvaluation();
} else if (type != null && type.equals("mass")) {
return new MassRuleEvaluation();
}
return null;
}
}
/*我的主類,我需要得到RuleEvaluation的一個實例,這裏的基礎的類型(dyamic) 不知道如何做到這一點。 */
public class MyApp {
public static void main(String args[]) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Spring-All-Module.xml");
String type = args[0];
/* i want to pass the above type String to the factory method and get the instance how to do that */
RuleEvaluation re = (HarmonyService) context.getBean("rulefactory") ;
}
}
/*我的Spring XML配置文件*/
Spring 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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="instanceMethodFactory" class="test.factory.RuleEvalFactory"> </bean>
<!-- i dont know how to pass the dynamic type from the Myapp main
method into this constructory argument -->
<bean id="rulefactory" factory-bean="instanceMethodFactory" factory-method="getInstance">
<constructor-arg index="0"> </constructor-arg>
</bean>
</beans>
請給在Spring XML和MYAPP主要方法如何注入式進工廠方法的的getInstance代碼。
問候, Raghu
的可能重複[如何獲取由FactoryBean Spring創建的bean管理?](http://stackoverflow.com/questions/4970297/how-to-get-beans-created-by-factorybean-spring-managed) – Bart
該abov e鏈接,不回答我的問題 – Raghu