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)类客户端{
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("resource/spring.xml");
Test t1=(Test)context.getBean("testObj");
t1.display();
}
}
当我只调用单个构造函数时它工作正常但在调用它们时它给出异常: 线程“main”中的异常 org.springframework.beans.factory.BeanCreationException:创建类路径资源 [resource/spring.xml] 中定义的名为“testObj”的 bean 时出错:无法解析匹配的构造函数(提示:指定索引/类型/为简单参数命名参数以避免类型歧义)
最佳答案
评论是对的。 spring 上下文文件的要点是构造类的实例或根据需要构造的原型(prototype)作为依赖项注入(inject)。
您只需调用一个构造函数来创建一个对象的实例(无论是 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>
关于java - spring中如何通过xml文件将值传递给多个参数化的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32416608/