Spring注入List/Map

Spring注入List/Map

XML方式

之前一直使用xml的方式進行Spring配置,對於內部元素爲String的List和Map屬性的注入一般爲如下方式:

<bean id = "testBean" class = "com.a.b.c.TestBean">
    <property name = "fieldMap">
        <map>
            <entry key = "field1" value = "value1"></entry>
            <entry key = "field2" value = "value2"></entry>
            <entry key = "field3" value = "value3"></entry>
        </map>
    </property>
    <property name = "fieldList">
        <list>
            <value>1</value>
            <value>2</value>
        </list>
    </property>
</bean>

如果內部元素爲Bean,則將value替換爲value-ref或元素即可。

當然,我們也可以使用Spring提供的schema擴展util來實現List和Map的聲明、注入:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util-2.5.xsd">
    <util:list list-class="java.util.ArrayList">
        <value>1</value>
        <value>2</value>
        <value>3</value>
    </util:list>
    <util:map map-class="java.util.HashMap">
        <entry key="Key1" value="1" />
        <entry key="Key2" value="2" />
        <entry key="Key3" value="3" />
    </util:map>
</beans>

註解方式

目前多用註解的方式來注入String類型的List和Map:

  • 在properties或yml中聲明Map或List的值:

    test.map = {key1:'value1',key2:'value2',key3:'value3'}
    test.list = value1,value2,value3

    爲了閱讀方便,建議properties文件中在比較長的行中使用’\’來斷行

  • 在目標Bean中使用@Value註解進行注入:

    @Value("#{'${test.list}'.split(',')}")
    private List<String> testList;
    @Value("#{${test.map}}")
    private Map<String,String> testMap;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章