习惯了把集合定义在一个类的字段中,今天遇到想重用集合的定义,竟然不知道单独的集合Bean应该怎么定义了,记之,以备后用。
对Map来说,有一种比较搓的方法,就是直接用Map的构造函数:
1
<
bean id
=
"
SymbolMap
"
class
=
"
java.util.HashMap
"
>
2 < constructor - arg >
3 < map >
4 < entry >
5 < key >< value ><! [CDATA[us;djia]] ></ value ></ key >
6 < value ><! [CDATA[us & dji]] ></ value >
7 </ entry >
8 </ map >
9 </ constructor - arg >
10 </ bean >
11
2 < constructor - arg >
3 < map >
4 < entry >
5 < key >< value ><! [CDATA[us;djia]] ></ value ></ key >
6 < value ><! [CDATA[us & dji]] ></ value >
7 </ entry >
8 </ map >
9 </ constructor - arg >
10 </ bean >
11
另一种稍微简单的方法:
1
<
bean id
=
"
emails
"
class
=
"
org.springframework.beans.factory.config.MapFactoryBean
"
>
2 < property name = " sourceMap " >
3 < map >
4 < entry key = " pechorin " value = " pechorin@hero.org " />
5 < entry key = " raskolnikov " value = " raskolnikov@slums.org " />
6 < entry key = " stavrogin " value = " stavrogin@gov.org " />
7 < entry key = " porfiry " value = " porfiry@gov.org " />
8 </ map >
9 </ property >
10 </ bean >
11
2 < property name = " sourceMap " >
3 < map >
4 < entry key = " pechorin " value = " pechorin@hero.org " />
5 < entry key = " raskolnikov " value = " raskolnikov@slums.org " />
6 < entry key = " stavrogin " value = " stavrogin@gov.org " />
7 < entry key = " porfiry " value = " porfiry@gov.org " />
8 </ map >
9 </ property >
10 </ bean >
11
对这种方法,Sping还提供了ListFactoryBean, SetFactoryBean等类,这貌似是Spring的一个可扩展框架,可以待以后进一步研究这个框架的实现方式。
最简单的一种方式就是直接用spring中提供的util包:
1
<
util:map id
=
"
emails
"
>
2 < entry key = " pechorin " value = " pechorin@hero.org " />
3 < entry key = " raskolnikov " value = " raskolnikov@slums.org " />
4 < entry key = " stavrogin " value = " stavrogin@gov.org " />
5 < entry key = " porfiry " value = " porfiry@gov.org " />
6 </ util:map >
7
2 < entry key = " pechorin " value = " pechorin@hero.org " />
3 < entry key = " raskolnikov " value = " raskolnikov@slums.org " />
4 < entry key = " stavrogin " value = " stavrogin@gov.org " />
5 < entry key = " porfiry " value = " porfiry@gov.org " />
6 </ util:map >
7
使用改方法时,xml文件头需要使用:
1
xmlns:util
=
"
http://www.springframework.org/schema/util
"
2 xsi:schemaLocation = " http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
3 http: // www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd ">
2 xsi:schemaLocation = " http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
3 http: // www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd ">
引用:
http://macrochen.iteye.com/blog/392616
http://springindepth.com/book/in-depth-ioc-collections.html