Spring系列教程——08集合注入讲解
文章目录
集合的注入都是给<property>添加子标签:
数组:<array>
List:<list>
Set:<set>
Map:<map> ,map存放k/v 键值对,使用<entry>描述
Properties:<props> <prop key=""></prop>
普通数据:<value>
引用数据:<ref>
编写类:
package domain;
import java.util.*;
public class Programmer {
@Override
public String toString() {
return "Programmer{" +
"works=" + Arrays.toString(works) +
", cars=" + cars +
", banks=" + banks +
", companies=" + companies +
", properties=" + properties +
'}';
}
String [] works;
List<String> cars;
Set<String> banks;
Map<String,String> companies;
Properties properties;
public String[] getWorks() {
return works;
}
public void setWorks(String[] works) {
this.works = works;
}
public List<String> getCars() {
return cars;
}
public void setCars(List<String> cars) {
this.cars = cars;
}
public Set<String> getBanks() {
return banks;
}
public void setBanks(Set<String> banks) {
this.banks = banks;
}
public Map<String, String> getCompanies() {
return companies;
}
public void setCompanies(Map<String, String> companies) {
this.companies = companies;
}
public Properties getProperties() {
return properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
}
beans.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="programmer" class="domain.Programmer">
<property name="works">
<array>
<value>运维</value>
<value>开发</value>
<value>产品</value>
</array>
</property>
<property name="cars">
<list>
<value>宝马</value>
<value>奔驰</value>
<value>本田</value>
</list>
</property>
<property name="banks">
<set>
<value>中国工商银行</value>
<value>中国邮政储蓄银行</value>
<value>中国人民银行</value>
</set>
</property>
<property name="companies">
<map>
<entry key="第一家公司" value="拼多多"></entry>
<entry key="第二家公司" value="字节跳动"></entry>
<entry key="第三家公司" value="阿里巴巴"></entry>
</map>
</property>
<property name="properties">
<props>
<prop key="name">jack</prop>
<prop key="password">123</prop>
<prop key="teleNumber">18872958601</prop>
</props>
</property>
</bean>
</beans>
测试代码如下:
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Programmer programmer = (Programmer)context.getBean("programmer");
System.out.println(programmer);
结果如下:
Programmer{
works=[运维, 开发, 产品],
cars=[宝马, 奔驰, 本田],
banks=[中国工商银行, 中国邮政储蓄银行, 中国人民银行],
companies={第一家公司=拼多多, 第二家公司=字节跳动, 第三家公司=阿里巴巴},
properties={name=jack, password=123, teleNumber=18872958601}}
<ref>标签读者可以自行操作实验。
上一篇:Spring系列教程——07Spring表达式讲解
下一篇:Spring系列教程——09Spring注解开发