javaspringconstructor-injection

Facing ambiguity in spring constructors, second constructor is getting called


I'm facing an issue which is producing an output which is not exactly per the norm. I have read that in case of constructor ambiguity the first constructor gets called. But I'm facing a completely different issue.

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 file -

<bean class="com.spring.Addition" name="addition1">
    <constructor-arg>
    <value>12</value>
    </constructor-arg>
    <constructor-arg>
    <value>34</value>
    </constructor-arg>
    </bean>

Main code -

Addition addition = (Addition)applicationContext.getBean("addition1");
System.out.println(addition);

Output-

Constructor : double, double
Addition [a=12, b=34]

My only concern here is why is the second constructor getting called here, when (int,int) constructor is defined before the (double,double) constructor?


Solution

  • You can avoid such ambiguity by specifying the exact data type for constructor, via type attribute as follows:

    <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>