Spring通过配置文件装配集合类型
通过配置文件可以轻松装配List、Set、Array、Map,以List 和Map为例:
注意:
bean中必须有get/set方法
具体的实现类型为bean中定义的类型
List、Set、Map中元素类型为自定义类型时用:ref
map中元素类型为自定义类型时用:key-ref,value-ref
Bean
package com.yolotproc.operation.utils; import java.util.ArrayList; import java.util.LinkedHashMap; public class Data { public ArrayList<String> list1; public ArrayList<Element> list2; public LinkedHashMap<String, String> map; ...省去get/set方法() }
package com.yolotproc.operation.utils; class Element{ String value;
...省去get/set方法()
}
xml
<beans> <bean id="ele1" class="com.yolotproc.operation.utils.Element"> <property name="value" value="elevalue1"/> </bean> <bean id="ele2" class="com.yolotproc.operation.utils.Element"> <property name="value" value="elevalue2"/> </bean> <bean id="data" class="com.yolotproc.operation.utils.Data"> <property name="map"> <map> <entry key="dirty1" value="DIRTY1"/> <entry key="dirty2" value="DIRTY2"/> <entry key="dirty3" value="DIRTY3"/> <entry key="dirty4" value="DIRTY4"/> </map> </property> <property name="list1"> <list> <value>str1</value> <value>str2</value> <value>str3</value> </list> </property> <property name="list2"> <list> <ref bean="ele1"/> <ref bean="ele2"/> </list> </property> </bean> </beans>
调用
@Controller public class AuthorizationController { @Autowired private Data data; }