Spring <Map>元素用来存储多个键值对属性,类型为java.util.Map;他的子标签<entry>用来定义Map中的键值实体,下面举例说明;
Article.java
这个article class有一个属性是作者联名信息,使用序号和作者名来构成一个Map属性.
import java.util.*;
public class Article
{
private String title;
private Map<String, String> authorsInfo;
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
public void setAuthorsInfo(Map<String, String> authorsInfo) {
this.authorsInfo = authorsInfo;
}
public Map<String, String> getAuthorsInfo() {
return authorsInfo;
}
}
spring-beans.xml:
<map>元素用于提供具体的实体键值配置,通过<entry>将序号和作者名称进行绑定注入。
<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-2.5.xsd">
<bean id="article" class="Article">
<property name="title" value="RoseIndia"/>
<property name="authorsInfo">
<map>
<entry key="1" value="Deepak" />
<entry key="2" value="Arun"/>
<entry key="3" value="Vijay" />
</map>
</property>
</bean>
</beans>
RunDemoMain.java
测试主程代码;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.*;
public class AppMain
{
public static void main( String[] args )
{
ApplicationContext appContext =
new ClassPathXmlApplicationContext(new String[] {"spring-beans.xml"});
Article article = (Article)appContext.getBean("article");
System.out.println("Article Title: "+article.getTitle());
Map<String, String> authorsInfo = article.getAuthorsInfo();
System.out.println("Article Author: ");
for (String key : authorsInfo.keySet()) {
System.out.println(key + " : "+(String)authorsInfo.get(key));
}
}
}
输出结果如下:
Article Title: RoseIndia
Article Author:
1 : Deepak
2 : Arun
3 : Vijay
转自: http://www.txdnet.cn/log/20221059000001.xhtm