- ·上一篇文章:Spring 注入内部 Beans
- ·下一篇文章:Spring Beans 自动装配
Spring 注入集合
{two=Pakistan, one=INDIA, three=USA, four=USA}注入 Bean 引用下面的 Bean 定义将帮助你理解如何注入 bean 的引用作为集合的元素。甚至你可以将引用和值混合在一起,如下所示:<?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-3.0.xsd"> <!-- Bean Definition to handle references and values --> <bean id="..." class="..."> <!-- Passing bean reference for java.util.List --> <property name="addressList"> <list> <ref bean="address1"/> <ref bean="address2"/> <value>Pakistan</value> </list> </property> <!-- Passing bean reference for java.util.Set --> <property name="addressSet"> <set> <ref bean="address1"/> <ref bean="address2"/> <value>Pakistan</value> </set> </property> <!-- Passing bean reference for java.util.Map --> <property name="addressMap"> <map> <entry key="one" value="INDIA"/> <entry key ="two" value-ref="address1"/> <entry key ="three" value-ref="address2"/> </map> </property> </bean></beans>为了使用上面的 bean 定义,你需要定义 setter 方法,它们应该也能够是用这种方式来处理引用。注入 null 和空字符串的值如果你需要传递一个空字符串作为值,那么你可以传递它,如下所示:<bean id="..." class="exampleBean"> <property name="email" value=""/></bean>前面的例子相当于 Java 代码:exampleBean.setEmail("")。如果你需要传递一个 NULL 值,那么你可以传递它,如下所示:<bean id="..." class="exampleBean"> <property name="email"><null/></property></bean>前面的例子相当于 Java 代码:exampleBean.setEmail(null)。
Spring 注入集合