一、环境准备
- 创建一个Maven项目
- pom.xml添加Spring依赖
- resources下添加spring的配置文件applicationContext.xml
- 项目中添加BookDao、BookDaoImpl类
public interface BookDao {
public void save();
}
public class BookDaoImpl implements BookDao {
private int[] array;
private List<String> list;
private Set<String> set;
private Map<String,String> map;
private Properties properties;
public void setArray(int[] array) {
this.array = array;
}
public void setList(List<String> list) {
this.list = list;
}
public void setSet(Set<String> set) {
this.set = set;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
public void save(){
System.out.println("book dao save...");
System.out.println("遍历数组:"+ Arrays.toString(array));
System.out.println("遍历List"+list);
System.out.println("遍历Set"+set);
System.out.println("遍历Map"+map);
System.out.println("遍历Properties"+properties);
}
}
- resources下提供spring配置文件
<?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="bookDao" class="itheima.dao.impl.BookDaoImpl">
</beans>
- 编写AppForDICollection运行类,加载Spring的IOC容器,并从中获取对应bean对象
public class AppForDICollection {
public static void main(String[] args) {
ApplicationContext c= new ClassPathXmlApplicationContext("applicationContext.xml");
BookDao bookdao= (BookDao) c.getBean("bookDao");
bookdao.save();
}
}
二、注入数组类型数据
<property name="array">
<array>
<value>100</value>
<value>200</value>
<value>300</value>
</array>
</property>
三、注入List类型数据
<property name="list">
<list>
<value>java</value>
<value>spring</value>
<value>mysql</value>
</list>
</property>
四、注入Map类型数据
<property name="map">
<map>
<entry key="contry" value="china"/>
<entry key="provice" value="henan"/>
<entry key="city" value="zhengzhou"/>
</map>
</property>
五、注入Set类型数据
<property name="set">
<set>
<value>springboot</value>
<value>vue</value>
<value>html</value>
</set>
</property>
六、注入Properties类型数据
<property name="properties">
<props>
<prop key="contry">china</prop>
<prop key="provice">guangdong</prop>
<prop key="city">guangzhou</prop>
</props>
</property>
配置完成后运行AppForCollection程序,运行结果为:
- property标签表示setter方式注入,构造方式注入constructor-arg标签内部也可以写、、、
- List的底层也是通过数组实现的,所以和标签是可以混用。
- 集合中要添加引用类型,只需要把标签改成标签,这种方式用的比较少。