我刚接触春天。
我有一个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;
}
}
/ *我的Main类,我需要根据类型(dyamic)获取RuleEvaluation的实例 不知道怎么做。 * /
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 main方法中的代码如何将类型注入工厂方法的getInstance。
此致 Raghu
答案 0 :(得分:1)
您需要在bean中指定构造函数参数
<bean id="myBean" class="A" scope="prototype">
<constructor-arg value="0"/> <!-- dummy value -->
</bean>
然后将值传递给bean工厂,
getBean("myBean", argument);