Spring使用工厂Bean和Utility Schema定义集合(1)
使用基本集合标记定义集合时,不能指定集合的实体类型,例如LinkedList,TreeSet或者TreeMap,而且,不能通过集合定义为可供其他Bean引用的单独Bean在不同的Bean中共享集合。
解决办法
Spring提供了两个选项来克服基本集合标记的不足,选项之一是使用对应的集合工厂Bean,如ListFactoryBean,SetFactoryBean,和MapFactoryBean。工厂Bean是用于创建其他Bean的特殊spring bean。第二个选项是util schema中使用集合标记。例如<util:list>,<util:set>和<util:map>
例如suffixes是实体类中定义的一个属性,类型为TreeSet,在spring中我们可以这样声明
1 <property name="suffixes"> 2 <bean class="org.springframework.beans.factory.config.SetFactoryBean"> 3 <property name="targetSetClass"> 4 <value>java.util.TreeSet</value> 5 </property> 6 <property name="sourceSet"> 7 <set> 8 <value>5</value> 9 <value>10</value> 10 <value>20</value> 11 </set> 12 </property> 13 </bean>
2,使用util schema中的集合标记定义集合并且设置其目标类(<util:set>的set-class属性)。但是必须在<beans>根元素中添加util schema定义
xmlns:util="http://www.springframework.org/schema/util"
xsi中添加http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
1 <property name="suffixes"> 2 <util:set set-class="java.util.TreeSet"> 3 <value>5</value> 4 <value>10</value> 5 <value>20</value> 6 </util:set> 7 </property>
当然也可以定义独立集合,供其他bean引用
1 <bean id = "suffixes" class="org.springframework.beans.factory.config.SetFactoryBean"> 2 <property name="sourceSet"> 3 <set> 4 <value>5</value> 5 <value>10</value> 6 <value>20</value> 7 </set> 8 </property> 9 </bean>
1 <util:set id="suffixes"> 2 <value>5</value> 3 <value>10</value> 4 <value>20</value> 5 </util:set>