Problem with dependency injection [SPR-17602] #22134
Labels
in: core
Issues in core modules (aop, beans, core, context, expression)
status: invalid
An issue that we don't feel is valid
Zohar Cohen opened SPR-17602 and commented
Hi,
I am facing a strange behavior with dependency injection in my project, there is an unexpected initialization of one of our constructors.
I am using Spring 5.0.6.RELEASE with XML configuration, we have the following structure:
Entity P - this class depended on two entities and a String:
Entity S - this class inject to the depended class, the class contains two constructors, we are initializing only the empty constructor
Entity D1
Entity D2
XML configuration:
Based on the configuration file, the following activities should happen:
S - calling to empty constructor.
P - we are calling to the contractors with two depended and MS string.
D2 - constructorr with one input 'MS'.
D1 - constructore with input 'MS'
The issue is that during the autowiring process Spring initializes the S constructor with the String argument which is not expected to be called.
Program Output:
S Argument Constructor!
D1 Constructor with input: MS
S Argument Constructor!
D2 Constructor with input: MS
P Constructor: D1: com.zohar.D1@4566e5bd, D2: com.zohar.D2@1ed4004b , Input: MS
S Empty Constructor!
This seems like a private case due to the second constructors that the depended class have (Seems like an issue with the reflection process).
The solution to this issue is to add the wrapper class as a type to the 'constructor-arg' tag:
<bean id="p" class="com.zohar.P">
<constructor-arg ref="d1" />
<constructor-arg ref="d2" />
<constructor-arg type="java.lang.String" value="MS" />
</bean>
<bean id="d1" class="com.zohar.D1">
<constructor-arg type="java.lang.String" value="MS" />
</bean>
<bean id="d2" class="com.zohar.D2">
<constructor-arg type="java.lang.String" value="MS" />
</bean>
The question is: why we are having this issue in case the type is not set where it is not mandatory?
Attached is the zip with this example.
Thank you very much in advance.
Zohar
Affects: 5.0.6
Attachments:
The text was updated successfully, but these errors were encountered: