Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to XML configure Spring bean for constructor injection when bean has varargs constructor

Tags:

java

spring

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     } } 
like image 696
Jen S. Avatar asked Apr 15 '09 12:04

Jen S.


People also ask

How do you specify the constructor values for a bean in the Spring configuration file?

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.

Which attribute is used to implement constructor injection in a bean?

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.

Is used to eliminate property and constructor arg tag in a bean file?

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.

What are the attributes used to avoid ambiguity in constructor injection?

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.


1 Answers

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> 
like image 171
dfa Avatar answered Sep 17 '22 15:09

dfa