通过示例三及后面的构造函数注入,知道了简单的注入方法,下面是集合与数组类型注入的示例。
1、编写数组集合的Bean类:
package test3.ioc;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Bean {
private String arr[];
@SuppressWarnings("rawtypes")
private List list;
@SuppressWarnings("rawtypes")
private Map map;
@SuppressWarnings("rawtypes")
private Set set;
public String[] getArr() {
return arr;
}
public void setArr(String arr[]) {
this.arr = arr;
}
@SuppressWarnings("rawtypes")
public List getList() {
return list;
}
@SuppressWarnings("rawtypes")
public void setList(List list) {
this.list = list;
}
@SuppressWarnings("rawtypes")
public Map getMap() {
return map;
}
@SuppressWarnings("rawtypes")
public void setMap(Map map) {
this.map = map;
}
@SuppressWarnings("rawtypes")
public Set getSet() {
return set;
}
@SuppressWarnings("rawtypes")
public void setSet(Set set) {
this.set = set;
}
}
2、配置applicationContext.xml:
<!-- 配置集合与数组类型注入初始值 -->
<bean id="bean" class="test3.ioc.Bean">
<!-- 数组属性注入值 -->
<property name="arr">
<value>c++,java,vb.net</value>
</property>
<!-- list集合属性注入值 -->
<property name="list">
<list>
<value>zhang</value>
<value>wang</value>
<value>lisi</value>
</list>
</property>
<!-- set集合属性注入值 -->
<property name="set">
<set>
<value>zhou---set</value>
<value>wang---set</value>
<value>lisi---set</value>
</set>
</property>
<!-- map属性注入值 -->
<property name="map">
<map>
<entry key="key1" value="zhang value1"></entry>
<entry key="key2" value="wang value2"></entry>
<entry key="key3" value="lisi value3"></entry>
</map>
</property>
</bean>
3、测试:
package test3;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import test3.ioc.Bean;
public class Test2 {
public static void main(String[] args) {
BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
Bean bean = (Bean)factory.getBean("bean");
Set set = bean.getSet();
Iterator it = set.iterator();
while (it.hasNext()) {
String s = (String)it.next();
System.out.println(s);
}
Map map = bean.getMap();
Set set1 = map.keySet();
Iterator it1 = set1.iterator();
while (it1.hasNext()) {
String key = (String)it1.next();
String value = (String)map.get(key);
System.out.println("key="+key+"value="+value);
}
}
}
注意:applicationContext.xml的配置请看前面入门内容及示例进行参考。