在此示例中,您将看到如何连接映射集合。为此,我们可以使用<map>Spring配置文件中的元素。此元素声明java.util.Map。我们将重用在上一个示例中使用的Bean。如何在Spring中使用list元素注入集合?
该<map>元素可以有许多<entry>与元素key和value-ref属性。
这是配置示例:
<?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="publisher"> <map> <entry key="publisher" value-ref="publisher"/> </map> </property> </bean> </beans>
该<map>元素可以具有许多<entry>元素。我们可以使用该key属性将字符串用作其键。如果您希望键在Spring上下文中引用其他bean,则可以使用key-ref。
将value-ref用于设置参考另一个Bean中的值。如果该值是简单值(例如字符串),则可以使用该value属性。
要运行它,请创建以下程序:
package org.nhooo.example.spring.collection; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class DemoMap { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext( new String[]{"collection-map.xml"}); Album album = (Album) context.getBean("album"); System.out.println("Album = " + album); } }
这是您将在控制台上看到的内容:
Album = Album{title='Please Please Me', year=1963, songs=[], publisher={publisher=Publisher{name=EMI Studios}}, props={}}