基于XML的DI-集合属性注入
bean(TheOne.java)
package com.hk.spring.di05;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class TheOne {
private School[] schools;
private List<String> myList;
private Set<String> mySet;
private Map<String,Object> myMap;
private Properties myProperties;
public void setSchools(School[] schools) {
this.schools = schools;
}
public void setMyList(List<String> myList) {
this.myList = myList;
}
public void setMySet(Set<String> mySet) {
this.mySet = mySet;
}
public void setMyMap(Map<String, Object> myMap) {
this.myMap = myMap;
}
public void setMyProperties(Properties myProperties) {
this.myProperties = myProperties;
}
@Override
public String toString() {
return "TheOne [schools=" + Arrays.toString(schools) + ", myList="
+ myList + ", mySet=" + mySet + ", myMap=" + myMap
+ ", myProperties=" + myProperties + "]";
}
}
配置(applicationContext.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="mySchool" class="com.hk.spring.di05.School">
<property name="schloolName" value="红林小学"/>
</bean>
<bean id="yourSchool" class="com.hk.spring.di05.School">
<property name="schloolName" value="东源小学"/>
</bean>
<bean id="theOne" class="com.hk.spring.di05.TheOne">
<!-- 为数组赋值 -->
<property name="schools">
<array>
<ref bean="mySchool"/>
<ref bean="yourSchool"/>
</array>
</property>
<!-- 为List赋值 -->
<property name="myList">
<list>
<value>张三</value>
<value>李四</value>
</list>
</property>
<!-- 为Set赋值 -->
<property name="mySet">
<set>
<value>北京</value>
<value>西京</value>
<value>南京</value>
</set>
</property>
<!-- 为Map赋值 -->
<property name="myMap">
<map>
<entry key="QQ" value="1326922252"></entry>
<entry key="weChat" value="a1326922252"></entry>
</map>
</property>
<!-- 为Properties赋值 -->
<property name="myProperties">
<props>
<prop key="账号">123456</prop>
<prop key="密码">789012</prop>
</props>
</property>
</bean>
</beans>
测试类(MyTest.java)
package com.hk.spring.di05;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Mytest {
@Test
public void test1(){
String resource = "com/hk/spring/di05/applicationContext.xml";
ApplicationContext ac = new ClassPathXmlApplicationContext(resource);
TheOne theOne = (TheOne) ac.getBean("theOne");
System.out.println(theOne);
}
}
结果
TheOne [schools=[School [schloolName=红林小学], School [schloolName=东源小学]], myList=[张三, 李四], mySet=[北京, 西京, 南京], myMap={QQ=1326922252, weChat=a1326922252}, myProperties={账号=123456, 密码=789012}]
简便写法
<!-- 为List赋值 -->
<property name="myList" value="张三,李四">
</property>
<!-- 为Set赋值 -->
<property name="mySet" value="北京,西京,南京">
</property>
仅限于字符串,复杂的结构不适用