Java Spring以什么顺序接受构造函数参数中的值
我试着注射DI。即使我没有在Java Spring以什么顺序接受构造函数参数中的值,java,spring,Java,Spring,我试着注射DI。即使我没有在中指定类型,这段代码也可以正常工作 三角形类: public class Triangle { private String type; private int height; public Triangle(int height) { this.height = height; } public Triangle(String type, int height) { this.type =
中指定类型,这段代码也可以正常工作
三角形类:
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>
但是,当我在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从
中获取值的顺序。一个简短的回答是:它以与类构造函数中描述的相同的顺序获取参数
(第7.4.1页)的证明:
构造函数参数解析匹配使用参数的
类型。如果的构造函数参数中不存在潜在的歧义
一个bean定义,然后是构造函数参数的顺序
在bean中定义的是这些参数的顺序
在创建bean时提供给相应的构造函数
实例化
帮我写了一个问题的答案
这是我的构造函数:
public Triangle(String type, int height) {
this.type = type;
this.height = height;
}
需要
type
(实例变量),类型为String
,作为第一个参数
int的height
作为第二个参数键入
因此,在spring.xml文件中,我们在
中提供的值应该与类的构造函数的顺序相同。所以当我尝试使用这些行时,抛出了一个异常
<constructor-arg value = "20" />
<constructor-arg value = "Isosceles"/>
原因是,
- 第一个参数“
20
”将作为字符串,并设置类型
实例变量李>
- 对于第二个参数“
Isosceles
”,height
实例发生类型不匹配(String
到int
转换)
变数
同意您的意见,您可以按照与类构造函数相同的顺序编写
。您还可以在
中指定索引,如下所示:
<constructor-arg index = "0" value = "Equilateral"></constructor-arg>
<constructor-arg index = "1" value= "20"></constructor-arg>
您的程序将毫无例外地执行。尽可能避免基于XML的配置。@Boristespider顺便问一下,为什么?只是wondering@AndremoniySpring社区正在远离基于XML的配置。据我所见,主要原因是基于Java的配置增加了更多的编译时类型安全性,因此更加健壮。这反映了JavaEE从web.xml
等移动到配置约定和基于元数据的配置的组合。@BoristheSpider这很有趣。我认为它朝着XML和Java注释之间平衡配置的方向发展。有关于这方面的权威文章吗?@Andremoniy如果你看看Spring Boot之类的东西,那几乎完全是基于约定(自动配置)的,能够使用JavaConfig覆盖行为。我不确定我是否见过任何我称之为权威的东西-我会想一想。现在,我发现当我互换使用
值时,出现了类型不匹配。
<constructor-arg index = "0" value = "Equilateral"></constructor-arg>
<constructor-arg index = "1" value= "20"></constructor-arg>
<constructor-arg index = "1" value= "20"></constructor-arg>
<constructor-arg index = "0" value = "Equilateral"></constructor-arg>