2013-10-01 71 views
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

+0

的可能重复[如何获取由FactoryBean Spring创建的bean管理?](http://stackoverflow.com/questions/4970297/how-to-get-beans-created-by-factorybean-spring-managed) – Bart

+0

该abov e链接,不回答我的问题 – Raghu

回答

1

您需要在bean来指定构造函数的参数,

<bean id="myBean" class="A" scope="prototype"> 
    <constructor-arg value="0"/> <!-- dummy value --> 
</bean> 

然后传递价值bean工厂,

getBean("myBean", argument);