《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