First I provide a small piece of code, then I ask for an explanation.
public class A { private String msg; private B b; public A () { System.out.println("No argument constructor is called"); } public A (B b) { System.out.println("Parameterized constructor is called"); this.b = b; }
================================================
<bean id="a" class="A" p:msg="hello" autowire="constructor"/> <bean id="b" class="B"/>
================================================
OUTPUT:
The parameterized constructor is called
This is normal behavior and understandable.
================================================
Now I am adding a new bean definition of class B as shown below.
<bean id="a" class="A" p:msg="hello" autowire="constructor"/> <bean id="b" class="B"/> <bean id="c" class="B"/>
So, as far as I know, since autowiring through the constructor internally uses 'byType', therefore, it will give an exception regarding violation of the uniqueness of the bean, for example, this scenario occurs if I use autowire = "byType".
But, oddly enough, the conclusion is given below.
OUTPUT:
The argument constructor is not called
==========================================
However, note that if the default constructor is not specified in class A, the expected exception is expected. So, is this the default behavior in a Spring IoC container? If so, please kindly explain this to me in detail.
Thanks in advance.
The question is also available on LinkedIn ( Spring autowiring through constructor uncertainty )