集合注入

依赖注入相关基础:依赖注入

环境配置

BookDao、BookDaoImpl类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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 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);
}
//setter....方法省略,使用工具生成
}

基础配置

1
2
3
4
5
6
7
<?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="com.itheima.dao.impl.BookDaoImpl"/>
</beans>

App 启动类

1
2
3
4
5
6
7
public class AppForDICollection {
public static void main( String[] args ) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
BookDao bookDao = (BookDao) ctx.getBean("bookDao");
bookDao.save();
}
}

注入集合配置

下面的所以配置方式,都是在 基础配置 中 bookDao 的 bean 标签中使用<property>进行注入

1. 注入数组类型数据

1
2
3
4
5
6
7
<property name="array">
<array>
<value>100</value>
<value>200</value>
<value>300</value>
</array>
</property>

2. 注入List类型数据

1
2
3
4
5
6
7
8
<property name="list">
<list>
<value>itcast</value>
<value>itheima</value>
<value>boxuegu</value>
<value>chuanzhihui</value>
</list>
</property>

3. 注入Set类型数据

1
2
3
4
5
6
7
8
<property name="set">
<set>
<value>itcast</value>
<value>itheima</value>
<value>boxuegu</value>
<value>boxuegu</value>
</set>
</property>

4. 注入Map类型数据

1
2
3
4
5
6
7
<property name="map">
<map>
<entry key="country" value="china"/>
<entry key="province" value="henan"/>
<entry key="city" value="kaifeng"/>
</map>
</property>

5. 注入Properties类型数据

1
2
3
4
5
6
7
<property name="properties">
<props>
<prop key="country">china</prop>
<prop key="province">henan</prop>
<prop key="city">kaifeng</prop>
</props>
</property>

运行结果

配置完成后,运行下看结果:

集合注入

说明

  • property标签表示setter方式注入,构造方式注入constructor-arg标签内部也可以写<array><list><set><map><props>标签
  • List的底层也是通过数组实现的,所以<list><array>标签是可以混用
  • 集合中要添加引用类型,只需要把<value>标签改成<ref>标签,这种方式用的比较少

集合注入
https://blog.pangcy.cn/2023/04/04/后端编程相关/java/spring/集合注入/
作者
ziYang | 子洋
发布于
2023年4月4日
许可协议