Google
 
Web unafbapune.blogspot.com

Saturday, June 25, 2005

 

Reusable String Array in Spring's Application Context

There is often the need to instantiate a single bean instance in the spring config file such that the bean is an array of strings that can be referenced in multiple other places. I tried the following which wouldn't work:
<bean id="reusableStringArray" class="[Ljava.lang.String">
<list>
<value>a</value>
<value>b</value>
</list>
</bean>
A similar requirement is to create a single bean instance which is a java.util.Properties object in the application context. It turns out I can define a list instead of a string-array. It does not matter because spring can transform the list to a string-array if necessary. Example:
<bean id="strings" class="java.util.ArrayList">
<constructor-arg index="0">
<list>
<value>a</value>
<value>b</value>
</list>
</constructor-arg>
</bean>
Similarly one should be able to create a Properties instance via a map element. Thanks to Andreas on this.

Also, Carlos Sanchez has a nice blog on this subject.

http://static.springframework.org/spring/docs/1.2.x/reference/beans.html#d0e2331

Comments:
I found a solution to this issue.

<bean id="myArrayList" class="java.util.ArrayList">
  <constructor-arg>
    <list>
      <bean class="yourclass">
          ...
    </list>
  </constructor-arg>
</bean>

<bean id="arrayUser" class="MyArrayUsingClass">
  <property name="arrayProperty">
    <bean factory-bean="myArrayList" factory-method="toArray"/>
  </property>
</bean>

Regards,
Stefan
 
Another solution:
<bean name="anArray" class="java.util.Arrays" factory-method="asList">
<constructor-arg>
<array>
<bean name="bean1" .. />
<bean name="bean2" .. />
</array>
</constructor-arg>
</bean>
 
Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?