Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

java - Spring overloaded constructor injection

This is the code :

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);
}

}

The Spring config-file is :

 <bean id="triangle" class="org.tester.Triangle">
    <constructor-arg value="20" />
    <constructor-arg value="10" />
</bean>

Is there any specific rule to determine which constructor will be called by Spring ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

So that resolves the ambiguity

EDIT :-

Please read more about this problem here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...