这篇文章来谈谈《Spring Framework 开发参考手册》的3.3.2小节中的集合对象注入。
在项目开发中,还是经常会用到集合对象注入的,不过感觉没有多少需要介绍的,这次就只给出实例了。
· 先建立一个包:javamxj.spring.basic.collections ,然后把以下4个文件放在这个包下。
package javamxj.spring.basic.collections; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; public class CollectionInjection { private Map someMap; private Properties someProps; private Set someSet; private List someList; public void setSomeProps(Properties someProps) { this.someProps = someProps; } public void setSomeList(List someList) { this.someList = someList; } public void setSomeMap(Map someMap) { this.someMap = someMap; } public void setSomeSet(Set someSet) { this.someSet = someSet; } public void displayInfo() { System.out.println("Map contents:"); for (Object key : someMap.keySet()) { System.out.println("Key: " + key + " - Value: " + someMap.get(key)); } System.out.println("\nProperties contents:"); for (Object key : someProps.keySet()) { System.out.println("Key: " + key + " - Value: " + someProps.get(key)); } System.out.println("\nSet contents:"); for (Object i : someSet) { System.out.println("Value: " + i); } System.out.println("\nList contents:"); for (Object i : someList) { System.out.println("Value: " + i); } } }
<?xml version="1.0" encoding="GBK"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="hello" class="javamxj.spring.basic.collections.Hello"/> <bean id="injectCollection" class="javamxj.spring.basic.collections.CollectionInjection"> <property name="someMap"> <map> <entry key="someValue" value="Hello javamxj!"/> <entry key="someBean"> <ref local="hello"/> </entry> </map> </property> <property name="someProps"> <props> <prop key="姓">张</prop> <prop key="名">小小</prop> </props> </property> <property name="someSet"> <set> <value>Hello World!</value> <ref local="hello"/> </set> </property> <property name="someList"> <list> <value>Hello World!</value> <ref local="hello"/> </list> </property> </bean> </beans>
·运行Main.java,输出结果如下:
Map contents:
Key: someValue - Value: Hello javamxj! Key: someBean - Value: 这是一个bean Properties contents:
Key: 姓 - Value: 张 Key: 名 - Value: 小小 Set contents:
Value: Hello World! Value: 这是一个bean List contents:
Value: Hello World! Value: 这是一个bean 这篇文章源代码下载(不包含库文件):http://free.ys168.com/?javamxj Spring目录下面的SpringBasic.zip。
注意: 需要使用JDK 5。 |