Is there a way to write a Spring bean in XML so that it uses constructor injection when that constructor has a varargs parameter type? IE, is there a way to specify an array the way you can specify a list?
For instance:
class MyClass { MyClass(String... args) { // rest omitted } }
applicationContext.xml We are providing the information into the bean by this file. The constructor-arg element invokes the constructor. In such case, parameterized constructor of int type will be invoked. The value attribute of constructor-arg element will assign the specified value.
The User bean class has three attributes viz. name, age and country. All the three attributes are set thru constructor injection. The toString() method of the User bean class is overridden to display the user object.
Using autowiring, it is possible to reduce or eliminate the need to specify properties or constructor arguments, saving a significant amount of typing.In an XmlBeanFactory, the autowire mode for a bean definition is specified by using the autowire attribute of the bean element. The following values are allowed.
The output is not as we expected, because Spring interprets the second and third argument of Employee constructor as string. To avoid this type of ambiguities we can specify the type of arguments by using type attribute of <constructor-arg/> element.
since args
is an array of String
you can use <list>
:
<bean name="myBean" class="MyClass"> <constructor-arg> <list> <value>111</value> <value>222</value> <value>333</value> <value>444</value> </list> </constructor-arg> </bean>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With