Declaring an array of objects in a Spring bean context

后端 未结 4 1644
遇见更好的自我
遇见更好的自我 2020-12-16 12:09

I\'m trying to create an array of objects in a Spring context file so I can inject it to a constructor that\'s declared like this:

public RandomGeocodingServ         


        
相关标签:
4条回答
  • 2020-12-16 12:33

    Spring can automatically convert a list into an array[]

    check it out http://forum.springsource.org/showthread.php?37767-Injecting-String-Array

    <bean name="test" class="Test">
       <property name="values" value="hugo,emil"></property>
    </bean>
    
    0 讨论(0)
  • 2020-12-16 12:33

    I'm actually using <array> tag to inject an array of objects into a bean and it works.

    Take a look at the following code...

        <bean id="song1" class="mx.com.company.songs.Song">
            <property name="name" value="Have you ever seen the rain?"/>        
        </bean>
        
        <bean id="song2" class="mx.com.company.songs.Song">
            <property name="name" value="La bamba"/>      
        </bean>
    
        <bean id="guitarPlayer" class="mx.com.company.musician.GuitarPlayer">
            <property name="songs">
                <array>
                    <ref bean="song1"/>
                    <ref bean="song2"/>
                </array>
            </property>
        </bean> 
    
    0 讨论(0)
  • 2020-12-16 12:37

    That's because there's no such thing as <array>, there's only <list>.

    The good news is that Spring will auto-convert between lists and arrays as required, so defined your array as a <list>, and Spring will be coerce it into an array for you.

    This should work:

    <bean id="googleGeocodingService" class="geocoding.GoogleGeocodingService">
       <constructor-arg ref="proxy" />
       <constructor-arg value="" />
    </bean>
    
    <bean id="geocodingService" class="geocoding.RandomGeocodingService">
        <constructor-arg>
            <list>
               <ref bean="googleGeocodingService"/>
            </list>
        </constructor-arg>
    </bean>
    

    Spring will also coerce a single bean into a list, if required:

    <bean id="geocodingService" class="geocoding.RandomGeocodingService">
        <constructor-arg>
           <ref bean="googleGeocodingService"/>
        </constructor-arg>
    </bean>
    
    0 讨论(0)
  • 2020-12-16 12:41

    Check out the util schema.

    0 讨论(0)
提交回复
热议问题