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>
4

3 回答 3

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>
于 2012-12-23T16:27:39.050 回答
2

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

于 2012-12-23T16:20:55.180 回答
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.

于 2012-12-23T16:28:45.213 回答