簡體   English   中英

Spring依賴注入工廠(動態值)

[英]Spring Dependency injection with factory(dynamic value)

我是春天的新手。

我有一個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類,我需要在這里基於type(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

您需要在Bean中指定構造函數參數,

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

然后將值傳遞給bean工廠,

getBean("myBean", argument);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM