前言
在之前的案例,列举的最多的是注入 对象。本篇博客则是补充说我们不仅可以注入对象 还可以注入其他的数据类型包括基本数据类型,引用数据类型。
注入基本数据类型
常见的基本数据类型有:short char int long float double boolean String
解决步骤
1 在配置文件中使用 property 标签 表示每一个 成员变量信息
2在目标类中 使用set 方法
demo案例
User 类
使用 Dl 注入 基本数据类型
spring 配置文件
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 class="fs.User" id="user" > <!-- 使用set方法注入属性--> <property name="name" value="李明"> </property> <property name="age" value="18"> </property> <property name="male" value="true"> </property> </bean> </beans>
UserTest 测试类
注入集合
常见的集合是 list ,set ,map
注入 list ,set ,map 和 基本数据类型的区别在于
在 property 标签下 都有对应的标签表示。如 list 有对应的list 标签,map 有 对应的map 标签
list,set,map
demo 案例
spring 配置文件
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 class="fs.User" id="user" > <!-- 使用set方法注入属性--> <property name="name" value="李明"> </property> <property name="age" value="18"> </property> <property name="male" value="true"> </property> // list <property name="list"> <list> <value>1</value> <value>"黎明"</value> <value>ture</value> <value>44444</value> </list> </property> // set <property name="set"> <set> <value>1</value> <value>"黎明"</value> <value>3333</value> <value>44444</value> </set> </property> </bean> </beans>
User 类
UserTest 测试类
map 集合和list,set 形式上是一样的,在对应的位置修改为 map 即可。
集合除了可以存储基本数据类型外,还可以存储 对象。我拿 list 举例
集合存储对象
demo 案例
准备工作
当前有 user ,student 类。现在要求 在 user 类有一个list 集合 把创建好的 student 对象以及自己罗列一些基本数据类型的数据存储到集合上,并打印出来。
spring 配置文件 需要修改部分
XML
<property name="list">
<list>
<value>1</value>
<value>"黎明"</value>
<value>ture</value>
<value>44444</value>
<ref bean="student"/>
</list>
</property>
<bean id="student" class="fs.Student"/>
其他不变,重新运行代码
![](https://i-blog.csdnimg.cn/direct/39415fe6455441b384bc18c489e4862e.png)