bean管理的集合属性注入,与单属性注入类型,稍有不同。小编在上篇文章:Spring — IOC 容器 之 Bean管理XML方式(属性注入) 介绍了单属性注入,今天来介绍一下集合属性的注入。Let go!
1,xml 配置文件:UserBeanConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 集合属性的注入-->
<bean id="listEntity" class="com.chaoge.nacos.demo.test.spring.entity.ListEntity">
<!--property标签即为bean的属性标签,name指明属性名-->
<property name="strings">
<!--array标签指明数组类型属性值-->
<array>
<value>strings-jack</value>
<value>strings-sam</value>
</array>
</property>
<property name="list">
<!--list标签指明list类型属性值-->
<list>
<value>list-tom</value>
<value>list-tom2</value>
</list>
</property>
<property name="set">
<!--set标签指明set类型属性值-->
<set>
<value>set-mike</value>
<value>set-mike2</value>
</set>
</property>
<property name="map">
<!--set标签指明set类型属性值-->
<map>
<!--entry标签指明map类型属性值, key-value = entry -->
<entry key="key1" value="value1"></entry>
<entry key="key2" value="value2"></entry>
</map>
</property>
</bean>
</beans>
上述及下述配置文件所用 ListEntity 实体类:
public class ListEntity {
private String[] strings;
private List<String> list;
private Set<String> set;
private Map<String, String> map;
//get set 方法略...
}
2,使用
public class BeanTest {
/**
* 集合属性的注入
*/
@Test
public void test4(){
ApplicationContext context =
new ClassPathXmlApplicationContext("com/chaoge/nacos/demo/test/spring/beanConfig/UserBeanConfig.xml");
ListEntity listEntity = context.getBean("listEntity", ListEntity.class);
System.out.println(listEntity);
}
}
输出:
D:\jdk\jdk1.8.0_171\bin\java.exe
ListEntity{strings=[strings-jack, strings-sam], list=[list-tom, list-tom2], set=[set-mike, set-mike2], map={key1=value1, key2=value2}}