Specifying a Vector-type bean property in Spring bean config XML file

In Spring IOC framework you can define bean properties of some collection types, such as List, Set, Propertie and Map. For example, for a bean that has a property “theList” of type “java.util.ArrayList”, you can specify the value as below:

<bean id="exampleBean" class="examples.ExampleBean">
    <property name="theList">
              <list>
                     <value type="java.lang.String">a String</value>
                     <value type="java.lang.Interger">100</value>
              </list>
       </property>
</bean>

This is fine. But if the “theList” is a java.util.Vector then the above won’t work because by default the List FactoryBean uses an ArrayList and can’t convert a java.util.ArrayList to java.util.Vector– you will get a conversion exception.

It seems Spring does not support “Vector” property type directly. You have to either define a custom PropertyEditor for Vector, or, work around it with something like below:

<property name="theList" >
                 <bean class="java.util.Vector">
                            <constructor-arg >
                                     <value type="int">2</value>
                            </constructor-arg>
                  </bean>
  </property>
  <property name="theList[0]" >
                <value type="java.lang.String">a String</value>
  </property>
  <property name="theList[1]" >
                <value type="java.lang.Integer">100</value>
  </property>

Or a better way like this:

<property name="theList" >
                 <bean class="java.util.Vector">
                            <constructor-arg >
                                     <list>
                                            <value type="java.lang.String"> a String</value>
                                            <value type="java.lang.Integer"> 100  </value>
                                     </list>
                            </constructor-arg>
                  </bean>
  </property>
Tags:

About: mmpower

Software Architect & Soccer Fan 黑超白袜 = IT 民工 + 摇滚大叔


Leave a Reply

Your email address will not be published. Required fields are marked *