本节书摘来自异步社区《Spring攻略(第2版)》一书中的第1章,第1.8节,作者: 【美】Gary Mak , Josh Long , Daniel Rubio著,更多章节内容可以访问云栖社区“异步社区”公众号查看
1.8.1 问题使用基本集合标记定义集合时,你不能指定集合的实体类,例如LinkedList、TreeSet或TreeMap,而且,你不能通过将集合定义为可供其他Bean引用的单独Bean在不同的Bean中共享集合。
1.8.2 解决方案Spring提供两个选项来克服基本集合标记的不足。选项之一是使用对应的集合工厂Bean,如ListFactoryBean、SetFactoryBean和MapFactoryBean。工厂Bean是用于创建其他Bean的特殊Spring bean。第二个选项是在Spring 2.x中引入的util schema中使用集合标记,如、和。
1.8.3 工作原理为集合指定实体类你可以使用集合工厂Bean定义一个集合,并且指定其目标类。例如,你可以为SetFactory Bean指定targetSetClass属性。然后Spring将为这个集合实例化指定的类。
<bean id="sequenceGenerator" class="com.apress.springrecipes.sequence.SequenceGenerator"> <property name="prefixGenerator" ref="datePrefixGenerator" /> <property name="initial" value="100000" /> <property name="suffixes"> <bean class="org.springframework.beans.factory.config.SetFactoryBean"> <property name="targetSetClass"> <value>java.util.TreeSet</value> </property> <property name="sourceSet"> <set> <value>5</value> <value>10</value> <value>20</value> </set> </property> </bean> </property> </bean>你也可以使用util schema中的集合标记定义集合并且设置其目标类(例如,利用的set-class属性)。但是你必须记住在根元素中添加util schema定义。
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"> <bean id="sequenceGenerator" class="com.apress.springrecipes.sequence.SequenceGenerator"> ... <property name="suffixes"> <util:set set-class="java.util.TreeSet"> <value>5</value> <value>10</value> <value>20</value> </util:set> </property> </bean> ... </beans>定义独立集合集合工厂Bean的另一个好处是可以将集合定义为独立Bean,供其他Bean引用。例如,你可以使用SetFactoryBean定义一个独立的Set。
<beans ...> <bean id="sequenceGenerator" class="com.apress.springrecipes.sequence.SequenceGenerator"> ... <property name="suffixes"> <ref local="suffixes" /> </property> </bean> <bean id="suffixes" class="org.springframework.beans.factory.config.SetFactoryBean"> <property name="sourceSet"> <set> <value>5</value> <value>10</value> <value>20</value> </set> </property> </bean> ... </beans>你也可以使用util schema中的标记定义一个独立Set。
<beans ...> <bean id="sequenceGenerator" class="com.apress.springrecipes.sequence.SequenceGenerator"> ... <property name="suffixes"> <ref local="suffixes" /> </property> </bean> <util:set id="suffixes"> <value>5</value> <value>10</value> <value>20</value> </util:set> ... </beans> 相关资源:敏捷开发V1.0.pptx