Spring重载构造函数注入 [英] Spring overloaded constructor injection
本文介绍了Spring重载构造函数注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是代码:
public class Triangle {
private String color;
private int height;
public Triangle(String color,int height){
this.color = color;
this.height = height;
}
public Triangle(int height ,String color){
this.color = color;
this.height = height;
}
public void draw() {
System.out.println("Triangle is drawn , +
"color:"+color+" ,height:"+height);
}
}
Spring配置-file是:
The Spring config-file is :
<bean id="triangle" class="org.tester.Triangle">
<constructor-arg value="20" />
<constructor-arg value="10" />
</bean>
是否有任何具体规则来确定Spring将调用哪个构造函数?
Is there any specific rule to determine which constructor will be called by Spring ?
推荐答案
这里,第一个参数将与每个方法的第一个参数匹配,然后匹配参数。
Here, the first argument will be matched to the first parameter of each method and then the parameter will be matched.
我会建议下面的解决方案有助于消除歧义
I would suggest the solution below to help remove ambiguity
如果你想打电话给你的第一个构造函数
If you want to call your first constructor use
<bean id="triangle" class="org.tester.Triangle">
<constructor-arg type="int" value="20" />
<constructor-arg type="java.lang.String" value="10" />
</bean>
如果你想打电话给你的第二个构造函数
If you want to call your second constructor use
<bean id="triangle" class="org.tester.Triangle">
<constructor-arg type="java.lang.String"value="20" />
<constructor-arg type="int" value="10" />
</bean>
这样就解决了歧义
编辑: -
请详细了解此问题 here 。
这篇关于Spring重载构造函数注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文