- 带有地图示例的Setter注入
像前面的示例一样, 它是论坛的示例, 其中一个问题可以有多个答案。
Question.java
此类包含三个属性, 即getters&setters和displayInfo()方法以显示信息。
package com.srcmini;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class Question {
private int id;
private String name;
private Map<
String, String>
answers;
//getters and setterspublic void displayInfo(){
System.out.println("question id:"+id);
System.out.println("question name:"+name);
System.out.println("Answers....");
Set<
Entry<
String, String>
>
set=answers.entrySet();
Iterator<
Entry<
String, String>
>
itr=set.iterator();
while(itr.hasNext()){
Entry<
String, String>
entry=itr.next();
System.out.println("Answer:"+entry.getKey()+" Posted By:"+entry.getValue());
}
}
}
applicationContext.xml
map的entry属性用于定义键和值信息。
<
?xml version="1.0" encoding="UTF-8"?>
<
beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<
bean id="q" class="com.srcmini.Question">
<
property name="id" value="http://www.srcmini.com/1">
<
/property>
<
property name="name" value="http://www.srcmini.com/What is Java?">
<
/property>
<
property name="answers">
<
map>
<
entry key="Java is a programming language"value="http://www.srcmini.com/Sonoo Jaiswal">
<
/entry>
<
entry key="Java is a Platform" value="http://www.srcmini.com/Sachin Yadav">
<
/entry>
<
/map>
<
/property>
<
/bean>
<
/beans>
Test.java
此类从applicationContext.xml文件获取Bean, 然后调用displayInfo()方法。
package com.srcmini;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class Test {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Question q=(Question)factory.getBean("q");
q.displayInfo();
}
}
下载此示例(使用MyEclipse IDE开发)
推荐阅读
- Spring非字符串集合的Setter注入(具有相关对象)示例
- Spring带有依赖对象的Setter注入示例
- Spring Setter对集合进行依赖注入示例
- 构造函数和setter注入之间有什么区别()
- Spring通过setter方法进行依赖注入示例
- Spring如何继承Bean(详细示例)
- 具有非字符串Map(具有从属对象)的构造函数注入示例
- Android_(游戏)打飞机02(游戏背景滚动)
- APP微信登录---第三方登录