依赖注入是IOC的具体实现;
通过注入给bean对象属性赋值;
注入内容
- 基本类型和String
- 其他的bean类型
- 复杂类型(集合类型)
通过构造函数注入
使用constructor-arg
,写在bean标签内部的子标签;此时bean对象的构造函数必须带参数。
- type:指定要注入的参数(在构造函数中)类型
- index:指定要注入的参数在构造函数中的索引位置
- name:在构造函数中的名称
- value:注入的数据内容,只能指定基本类型和String类型
- ref:指定其它在spring容器中的bean类型
<bean id="helloWorld" class="spring.HelloWorld" scope="singleton">
<constructor-arg name="name" value="wangcf"></constructor-arg>
<constructor-arg name="age" value="23"></constructor-arg>
<constructor-arg name="birthdate" ref="nowDate"></constructor-arg>
</bean>
<bean id="nowDate" class="java.util.Date"></bean>
通过set方法注入
使用property
- name:属性的set方法名称
- value:注入的数据内容,只能指定基本类型和String类型
- ref:指定其它在spring容器中的bean类型
<bean id="helloWorld" class="spring.HelloWorld" scope="singleton">
<property name="name" value="wangcf"></property>
<property name="age" value="24"></property>
<property name="birthdate" ref="nowDate"></property>
</bean>
<bean id="nowDate" class="java.util.Date"></bean>
p
名称空间注入
导入
<beans
xmlns:p="http://www.springframework.org/schema/p" >
直接在bean标签上注入
<bean id="helloWorld" class="spring.HelloWorld" p:name="zs"></bean>
注入复杂类型数据
array
、list
、set
可互用
<bean class="spring.HelloWorld" id="helloWorld">
<property name="myArray">
<array>
<value>1</value>
<value>2</value>
</array>
<list></list>
<set></set>
</property>
</bean>
map
、props
可互用
<bean class="spring.HelloWorld" id="helloWorld">
<property name="myArray">
<map>
<entry key="a" value="1"></entry>
<entry key="b">
<value>2</value>
</entry>
</map>
</property>
</bean>
map
、props
可互用
<bean class="spring.HelloWorld" id="helloWorld">
<property name="myArray">
<props>
<prop key="a" value="1"></prop>
</props>
</property>
</bean>