我正面临一个问题,它产生的输出不完全符合规范。我读到过,在构造函数不明确的情况下,第一个构造函数被调用。但我面对的是一个完全不同的问题。
My class -
public class Addition {
private int a;
private int b;
public Addition() {
super();
// TODO Auto-generated constructor stub
}
public Addition(int a, int b) {
super();
this.a = a;
this.b = b;
System.out.println("Constructor : int, int");
}
public Addition(double a, double b) {
super();
this.a = (int)a;
this.b = (int)b;
System.out.println("Constructor : double, double");
}
public void doSum() {
System.out.println("Sum is -> "+(this.a+this.b));
}
@Override
public String toString() {
return "Addition [a=" + a + ", b=" + b + "]";
}
}
XML文件-
<bean class="com.spring.Addition" name="addition1">
<constructor-arg>
<value>12</value>
</constructor-arg>
<constructor-arg>
<value>34</value>
</constructor-arg>
</bean>
主代码-
Addition addition = (Addition)applicationContext.getBean("addition1");
System.out.println(addition);
输出——
Constructor : double, double
Addition [a=12, b=34]
我唯一关心的是为什么第二个构造函数在这里被调用,当(int,int)构造函数在(double,double)构造函数之前定义?
您可以通过以下type
属性为构造函数指定确切的数据类型来避免这种歧义:
<bean class="com.spring.Addition" name="addition1">
<constructor-arg type="int">
<value>12</value>
</constructor-arg>
<constructor-arg type="int">
<value>34</value>
</constructor-arg>
</bean>