面对 spring 构造函数中的歧义,第二个构造函数被调用
Facing ambiguity in spring constructors, second constructor is getting called
我遇到了一个问题,即生成的输出不完全符合规范。我读过,如果构造函数不明确,则会调用第一个构造函数。但我面临着一个完全不同的问题。
我的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>
我遇到了一个问题,即生成的输出不完全符合规范。我读过,如果构造函数不明确,则会调用第一个构造函数。但我面临着一个完全不同的问题。
我的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>