我们如何在spring中通过xml文件将值传递给多参数化构造函数?

时间:2015-09-05 18:53:54

标签: java xml spring

        I have three files
        1) Test.java (in which i have created two parameterized constructor)
        2) spring.xml (xml file)
        3) Client.java(in which i have created main method)

        1)Test.java

        public class Test {
        private String name,email;
        private int age;

            public Test(String name,int age)
            {
                this.name=name;
                this.age=age;
            }
            public Test(String name)
            {
                this.name=name;
            }
            public void display()
            {
                System.out.println("First Constructor "+name+" "+age);
                System.out.println("Second Constructor "+name);

            }
        }



    2) spring.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
    "http://www.springframework.org/dtd/spring-beans-2.0.dtd">

    <beans>
    <bean id="testObj" class="Test" >

    <constructor-arg value="name"  index="0"/>

    <constructor-arg value="123"  index="1"/>

    <constructor-arg value="name"/>

    </bean>
    </beans>

3) Client.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Client {

    public static void main(String[] args) {

        ApplicationContext context=new ClassPathXmlApplicationContext("resource/spring.xml");
        Test t1=(Test)context.getBean("testObj");
        t1.display();
    }

}

当我只调用单个构造函数时,它的工作正常但是在调用它们的情况下它给出了异常: 线程&#34; main&#34;中的例外情况org.springframework.beans.factory.BeanCreationException:创建名为&#39; testObj&#39;的bean时出错在类路径资源[resource / spring.xml]中定义:无法解析匹配的构造函数(提示:为简单参数指定索引/类型/名称参数以避免类型歧义)

2 个答案:

答案 0 :(得分:4)

评论是对的。 spring上下文文件的要点是构造一个类或原型的实例,根据需要构造它作为依赖项注入。

您只需要调用一个构造函数来创建对象的实例(无论spring是构造您的对象还是您自己在代码中执行它)。

你总是可以在spring上下文中放置同一个类的多个对象,在每种情况下调用不同的构造函数。

<bean id="testObj" class="Test" >
 <constructor-arg value="name" index="0"/>
 <constructor-arg value="123" index="1"/> 
 </bean>
<bean id="testObj1" class="Test" >
 <constructor-arg value="name"/> 
</bean>

答案 1 :(得分:0)

您可以尝试参数化的JUnits。您可以在不同的测试场景中提供尽可能多的测试。 You can check here