在Spring的配置文件applicationContext.xml中,可以通过<list/>,<set/>,<list/>和<map/>标签来注入设置与集合类型相对应的List,Set,数组和Map集合的值.
首先设计一个类,代码如下:
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ComAttribute {
private List listValue;
private Set setValue;
private String[] arrayValue;
private Map mapValue;
public List getListValue() {
return listValue;
}
public void setListValue(List listValue) {
this.listValue = listValue;
}
public Set getSetValue() {
return setValue;
}
public void setSetValue(Set setValue) {
this.setValue = setValue;
}
public String[] getArrayValue() {
return arrayValue;
}
public void setArrayValue(String[] arrayValue) {
this.arrayValue = arrayValue;
}
public Map getMapValue() {
return mapValue;
}
public void setMapValue(Map mapValue) {
this.mapValue = mapValue;
}
}
接着设计一个测试类,代码如下:
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import junit.framework.TestCase;
public class testComAttribute extends TestCase {
private BeanFactory factory;
//重写TestCase父类
protected void setup() throws Exception {
factory = new ClassPathXmlApplicationContext("applicationContext.xml");
}
public void testInjection() {
//调用工厂Bean
ComAttribute comAttribute = factory.getBean("comAttribute");
System.out.println("comAttribute.listValue = " + comAttribute.getListValue());
System.out.println("comAttribute.setValue = " + comAttribute.getSetValue());
System.out.println("comAttribute.arrayValue = " + comAttribute.getArrayValue());
System.out.println("comAttribute.mapValue = " + comAttribute.getMapValue());
}
}
applicationContext.xml文件的内容如下:
<bean id="comAttribute" class=".../ComAttribute">
<property name="listValue">
<list>
<value>list_1</value>
<value>list_2</value>
</list>
</property>
<property name="setValue">
<set>
<value>set_1</value>
<value>set_2</value>
</set>
</property>
<property name="arrayValue">
<list>
<value>array_1</value>
<value>array_2</value>
</list>
</property>
<property name="mapValue">
<map>
<entry key="key_1" value="value_1"/>
<entry key="key_2" value="value_2"/>
</map>
</property>
</bean>
注意:标记<map>中的子标记<entry>中的key和value的值不能是bean,list,set,map和value元素;同时标记<set>中子标记<value>的值也不能是上面的元素.
分享到:
评论