<分区>
我尝试了 DI 的构造函数注入(inject)。即使我没有指定 type
,这段代码也能正常工作在 <constructor-arg>
.
三角形类:
public class Triangle {
private String type;
private int height;
public Triangle(int height) {
this.height = height;
}
public Triangle(String type, int height) {
this.type = type;
this.height = height;
}
public Triangle(String type) {
this.type = type;
}
public void draw(){
System.out.println(getType()+ " Triangle drawn with height = "+getHeight());
}
public String getType() {
return type;
}
public int getHeight() {
return height;
}
}
配置文件,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 = "triangle" class = "model.Triangle">
<constructor-arg value = "Isosceles"/>
<constructor-arg value = "20" />
</bean>
</beans>
驱动类(main
方法):
public class Driver {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
Triangle triangle = (Triangle) context.getBean("triangle");
triangle.draw();
}
}
但是,当我尝试 <constructor-arg>
的行时在 spring.xml
中可互换,抛出如下异常:
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'triangle' defined in class path resource [spring.xml]: Could not resolve matching constructor (hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)
我无法弄清楚 Spring 从 <constructor-arg>
中获取值的顺序。 .