《Spring攻略(第2版)》——1.8 使用工厂Bean和Utility Schema定义集合
本节书摘来自异步社区《Spring攻略(第2版)》一书中的第1章,第1.8节,作者: 【美】Gary Mak , Josh Long , Daniel Rubio着,更多章节内容可以访问云栖社区“异步社区”公众号查看
1.8 使用工厂Bean和Utility Schema定义集合
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中使用集合标记,如util:list、util:set和util:map。
1.8.3 工作原理
为集合指定实体类
你可以使用集合工厂Bean定义一个集合,并且指定其目标类。例如,你可以为SetFactory Bean指定targetSetClass属性。然后Spring将为这个集合实例化指定的类。
<bean
>
<property name="prefixGenerator" ref="datePrefixGenerator" />
<property name="initial" value="100000" />
<property name="suffixes">
<bean >
<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中的集合标记定义集合并且设置其目标类(例如,利用util:set的set-class属性)。但是你必须记住在根元素中添加util schema定义。
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns:util="https://www.springframework.org/schema/util"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans-3.0.xsd
https://www.springframework.org/schema/util
https://www.springframework.org/schema/util/spring-util-3.0.xsd">
<bean
>
...
<property name="suffixes">
<util:set set->
<value>5</value>
<value>10</value>
<value>20</value>
</util:set>
</property>
</bean>
...
</beans>
定义独立集合
集合工厂Bean的另一个好处是可以将集合定义为独立Bean,供其他Bean引用。例如,你可以使用SetFactoryBean定义一个独立的Set。
<beans ...>
<bean
>
...
<property name="suffixes">
<ref local="suffixes" />
</property>
</bean>
<bean
>
<property name="sourceSet">
<set>
<value>5</value>
<value>10</value>
<value>20</value>
</set>
</property>
</bean>
...
</beans>
你也可以使用util schema中的util:set标记定义一个独立Set。
<beans ...>
<bean
>
...
<property name="suffixes">
<ref local="suffixes" />
</property>
</bean>
<util:set >
<value>5</value>
<value>10</value>
<value>20</value>
</util:set>
...
</beans>
最后更新:2017-05-31 15:31:27