spring容器注入

跳转到项目地址

如果是String 这种简单类型的数据,spring注入如下:

User.java

1
2
3
4
5
6
7
8
9
public class User{
private String name;

public void setName(String name){
this.name = name;
}

//...
}

beans.xml

1
2
3
4
5
<!--前面的省略-->
<bean id="user" class="com.xxx.User">
<property name="name" value="张三" />
</bean>

但是,如果要注入的不是如String 这种简单类型数据,而是array、list、map、prop。。。这种容器类型数据,应该如何写bean,下面是模板:

官方文档说明

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
32
33
34
35
36
37
38
39
40
41
42
43
<bean id="moreComplexObject" class="example.ComplexObject">
<!-- array注入 -->
<property name="books">
<array>
<value>《abc》</value>
<value>《defg》</value>
<value>《hijk》</value>
</array>
</property>

<!-- prop注入 -->
<property name="adminEmails">
<props>
<prop key="administrator">administrator@example.org</prop>
<prop key="support">support@example.org</prop>
<prop key="development">development@example.org</prop>
</props>
</property>

<!-- list注入 -->
<property name="someList">
<list>
<value>a list element followed by a reference</value>
<ref bean="myDataSource" />
</list>
</property>

<!-- map -->
<property name="someMap">
<map>
<entry key="an entry" value="just some string"/>
<entry key ="a ref" value-ref="myDataSource"/>
</map>
</property>

<!-- set注入 -->
<property name="someSet">
<set>
<value>just some string</value>
<ref bean="myDataSource" />
</set>
</property>
</bean>

例如要往下面这些属性注入值

image-20210730172726839

beans.xml:

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="address" class="com.ajream.pojo.Address" >
<property name="addr" value="西安"/>
</bean>

<bean id="student" class="com.ajream.pojo.Student">

<!-- 普通值注入-->
<property name="name" value="王二"/>
<property name="age" value="30"/>

<!-- bean注入-->
<property name="address" ref="address" />

<!-- 数组array注入-->
<property name="books">
<array>
<value>《计算机技术》</value>
<value>《操作系统》</value>
<value>《数据结构》</value>
</array>
</property>

<!-- set注入-->
<property name="games">
<set>
<value>王者荣耀</value>
<value>少年三国志</value>
</set>
</property>

<!-- list注入-->
<property name="hobbies">
<list>
<value>打游戏</value>
<value>打羽毛球</value>
</list>
</property>

<!-- map注入-->
<property name="grade">
<map>
<entry key="高等数学" value="85"/>
<entry key="大学英语" value="90"/>
<entry key="java基础" value="98"/>
</map>
</property>

<!-- prop注入,类似map-->
<property name="info">
<props>
<prop key="email">administrator@example.org</prop>
<prop key="phone">13389453895</prop>
<prop key="QQ-number">456382987</prop>
</props>
</property>

</bean>

</beans>

输出预览:

image-20210730173016148