【问题标题】:Spring Dependency injection with factory(dynamic value)带工厂的 Spring 依赖注入(动态值)
【发布时间】:2013-10-01 06:44:24
【问题描述】:

我是春天的新手。

我有一个规则工厂,它会从静态方法返回一个实例 基于类型值

现在我将从主要方法中获取类型,参数。

现在我想将参数类型传递给工厂方法 getInstance 类型参数。

怎么做。

/* 工厂类,getInstance 将返回 RuleEvaluation 的子类型,为简单起见,我没有 为 SingleRuleEvaluation 和 MassRuleEvaluation 提供了实现类。基本上这两个类都实现了 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 的实例 不知道该怎么做。 */

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。

问候, 拉古

【问题讨论】:

标签: java spring


【解决方案1】:

你需要在bean中指定构造函数参数,

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

然后将值传给bean工厂,

getBean("myBean", argument);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多