1

Suppose I have a class MyClass which can be instantiated either with String or it have predefined static instances inside a class.

Something like this:

public class MyClass {

   public final static MyClass A = new MyClass("A");
   public final static MyClass B = new MyClass("B");
   public final static MyClass C = new MyClass("C");
   ...

   public MyClass(String name) {
      ...
   }
}

Is it possible to create an ArrayList<MyClass> bean in Spring config somehow? Something like

<bean id="sequence" class="...ArrayList"> 
    <member class="...MyClass" value="A"/>
    <member ... />
    ....
</bean>

UPDATE 1

Is it possible to write following way:

<bean id="sequence" class="...ArrayList"> 
  <constructor-arg>
     <list>
         <bean class="...MyClass" constructor-arg="A"/>
         <bean class="...MyClass" constructor-arg="B"/>
         <bean class="...MyClass" constructor-arg="C"/>
     </list>
  </constructor-arg>
</bean>
Dims
  • 47,675
  • 117
  • 331
  • 600
  • I think you will find this useful : http://stackoverflow.com/questions/2416056/how-to-define-a-list-bean-in-spring – user1885297 Dec 23 '12 at 16:27

3 Answers3

3

You should have a look at the Collections section in the spring IOC documentation.

<bean id="moreComplexObject" class="example.ComplexObject">
  <property name="someList">
    <list>
      <value>a list element followed by a reference</value>
      <ref bean="myDataSource" />
    </list>
  </property>    
</bean>
micha
  • 47,774
  • 16
  • 73
  • 80
2

Yes. You can even create it as a standalone bean. See this thread for two examples.

Jeanne Boyarsky
  • 12,156
  • 2
  • 49
  • 59
2

You could do:

<bean id="myClassA" class="org.foo.MyClass"> 
   <constructor-arg>
     <bean class="java.lang.String">
       <constructor-arg value="A"/>
     </bean>   
   <constructor-arg>
</bean>

<bean id="sequence" class="java.util.ArrayList">
    <constructor-arg>
        <list>
            <ref bean="myClassA" />
            ...
        </list>
    </constructor-arg>
</bean>

Note, however, that the most common approach is to inject a list directly into a bean rather than wrapping a list within a list first.

Reimeus
  • 158,255
  • 15
  • 216
  • 276