Java如何在Spring中使用props元素注入集合?

这次,我们将演示如何注入java.util.Properties。此类存储键值对数据,其中键和值都在字符串中。您可以使用<props>元素来连接属性集合。

我们在本示例中使用的bean取自上一个示例。如何在Spring中使用list元素注入集合?

让我们创建配置文件并调用它CollectionProps.xml。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="song1">
        <property name="title" value="I Saw Her Standing There" />
        <property name="writer" value="Beatles" />
    </bean>

    <bean id="song2">
        <property name="title" value="Misery" />
        <property name="writer" value="Beatles" />
    </bean>

    <bean id="song3">
        <property name="title" value="Anna (Go to Him)" />
        <property name="writer" value="Beatles" />
    </bean>

    <bean id="publisher">
        <property name="name" value="EMI Studios"/>
    </bean>

    <bean id="album">
        <property name="title" value="Please Please Me"/>
        <property name="year" value="1963"/>
        <property name="props">
            <props>
                <prop key="color">Black</prop>
                <prop key="type">CD</prop>
                <prop key="duration">1 Hour</prop>
            </props>
        </property>
    </bean>

</beans>

要连接属性集合,我们使用<props>元素。此元素可以包含很多元素<prop>。该key元素的属性定义的属性的键。该属性的值在此元素的主体中设置。

和往常一样,让我们创建一个简单的程序来运行它:

package org.nhooo.example.spring.collection;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DemoProps {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext(
            new String[]{"collection-props.xml"});

        Album album = (Album) context.getBean("album");
        System.out.println("Album = " + album);
    }
}

运行它时,它将产生以下输出:

Album = Album{title='Please Please Me', year=1963, songs=[], publisher={}, props={color=Black, type=CD, duration=1 Hour}}