DI依赖注入(Dependency Injection)
简介
依赖注入次要包含两个局部:
- 依赖:对象的创立依赖于容器
- 注入:对象的属性依赖于容器的注入
结构器注入
请查看Spring创建对象的形式。
set注入
<?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="address" class="com.spring.pojo.Address"> <property name="province" value="河南省"></property> <property name="city" value="郑州"></property> </bean> <bean id="student" class="com.spring.pojo.Student"><!-- 字符串--> <property name="name" value="张三"></property><!-- 数字--> <property name="age" value="22"></property><!-- 对象--> <property name="address" ref="address"></property><!-- 数组--> <property name="cards"> <array> <value type="java.lang.String">三好学生</value> <value type="java.lang.String">优良班干部</value> </array> </property><!-- set--> <property name="friends"> <set> <value type="java.lang.String">李四</value> <value>王五</value> </set> </property><!-- list--> <property name="plans"> <list> <value>学习</value> <value>健身</value> <value>吃饭</value> </list> </property><!-- 空值--> <property name="wife"> <null/> </property><!-- Properties--> <property name="properties"> <props> <prop key="父亲">老张</prop> <prop key="哥哥">大张</prop> <prop key="弟弟">张宝儿</prop> </props> </property><!-- boolean--> <property name="bad"> <value>true</value> </property><!-- map--> <property name="scores"> <map> <entry key="Chinese" value="140"></entry> <entry key="Math" value="140"></entry> <entry key="English" value="140"></entry> </map> </property> </bean></beans>
其它形式注入
命名空间的形式简化了需要:
- p命名空间: 也就是set形式的注入
- c命名空间: 也就是结构器形式的注入
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:c="http://www.springframework.org/schema/c" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="address" class="com.spring.pojo.Address"> <property name="province" value="河南省"></property> <property name="city" value="郑州"></property> </bean> <bean id="address" class="com.spring.pojo.Address" p:province="河南省" p:city="郑州"></bean> <bean id="address" class="com.spring.pojo.Address" c:province="河南省" c:city="郑州"></bean><beans/>