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;

猜你喜欢

转载自blog.csdn.net/woshismyawei/article/details/80667246
今日推荐