使用value属性和使用标签的ref属性在你的bean配置文件中的对象引用,这两种情况下可以处理单值到一个bean,如果你想通过多元值,如Java Collection类型List, Set, Map 及 Properties。要处理这种情况,Spring提供了四种类型的如下集合的配置元素:
可以使用 或 来连接任何实现java.util.Collection或数组。
会遇到两种情况(a)将收集的直接的值及(b)传递一个bean的引用作为集合的元素之一。
例子:我们使用Eclipse IDE,然后按照下面的步骤来创建一个Spring应用程序:
这里是JavaCollection.java文件的内容:
package com.yiibai;
import java.util.*;
public class JavaCollection {
List addressList;
Set addressSet;
Map addressMap;
Properties addressProp;
// a setter method to set List
public void setAddressList(List addressList) {
this.addressList = addressList;
}
// prints and returns all the elements of the list.
public List getAddressList() {
System.out.println("List Elements :" + addressList);
return addressList;
}
// a setter method to set Set
public void setAddressSet(Set addressSet) {
this.addressSet = addressSet;
}
// prints and returns all the elements of the Set.
public Set getAddressSet() {
System.out.println("Set Elements :" + addressSet);
return addressSet;
}
// a setter method to set Map
public void setAddressMap(Map addressMap) {
this.addressMap = addressMap;
}
// prints and returns all the elements of the Map.
public Map getAddressMap() {
System.out.println("Map Elements :" + addressMap);
return addressMap;
}
// a setter method to set Property
public void setAddressProp(Properties addressProp) {
this.addressProp = addressProp;
}
// prints and returns all the elements of the Property.
public Properties getAddressProp() {
System.out.println("Property Elements :" + addressProp);
return addressProp;
}
}
以下是MainApp.java文件的内容:
package com.yiibai;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
JavaCollection jc=(JavaCollection)context.getBean("javaCollection");
jc.getAddressList();
jc.getAddressSet();
jc.getAddressMap();
jc.getAddressProp();
}
}
以下是配置文件beans.xml文件里面有配置的集合的所有类型:
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-3.0.xsd">
INDIA
Pakistan
USA
USA
INDIA
Pakistan
USA
USA
INDIA
Pakistan
USA
USA
创建源代码和bean配置文件完成后,让我们运行应用程序。如果应用程序一切顺利,这将打印以下信息:
List Elements :[INDIA, Pakistan, USA, USA]
Set Elements :[INDIA, Pakistan, USA]
Map Elements :{1=INDIA, 2=Pakistan, 3=USA, 4=USA}
Property Elements :{two=Pakistan, one=INDIA, three=USA, four=USA}
注入Bean引用:下面bean定义将帮助您了解如何注入bean的引用作为集合的元素之一。甚至可以混合引用和值都在一起,如下图所示:
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-3.0.xsd">
Pakistan
Pakistan
使用上面的bean定义,需要定义这样一种方式,他们应该能够处理的参考,以及setter方法。
注入null和空字符串的值如果需要传递一个空字符串作为值,如下所示:
前面的例子等同于Java代码: exampleBean.setEmail("")
如果需要传递一个null值,如下所示:
前面的例子等同于Java代码:exampleBean.setEmail(null)