spring之IOC详解一
Inversion of Control,控制反转;即对象的依赖关系由容器来管理。
2.什么是DI(依赖注入)? Dependency Injection
容器通过调用对象的set方法或者构造器来完成依赖关系的建立。
1)调用对象的set方法
a.提供相应的set方法
b.要提供不带参的构造器
c.在配置文件当中,使用<property>元素来完成依赖关系的建立。
2)调用对象的构造器
a.提供相应的构造器
b.在配置文件当中,使用<construct-arg>来完成依赖关系的建立。
3)自动装配(了解)
autowire:
byName:容器依据属性名查找对应的bean,然后调用对应的set方法来完成注入。
byType:容器依据属性类型查找对应的bean,然后调用对应的set方法来完成注入。
注意:有可能有多个bean满足条件,会报错。constructor:容器依据属性类型查找对应的bean,然后调用对应的构造器来完成注入。
注意:有可能有多个bean满足条件,会报错。
代码示例:
applicationContext.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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<!-- 1.setter注入 -->
<bean id="mp" class="container.ioc.MobilePhone" lazy-init="true">
<property name="brand" value="华为mate8"/>
<property name="cpu" value="麒麟"/>
<property name="ram" value="3g"/>
</bean>
<!--
2.构造器注入
index指定对应参数的下标,从0开始
-->
<bean id="m" class="container.ioc.Manager">
<constructor-arg index="0" value="小李子"/>
<constructor-arg index="1" value="教学部"/>
</bean>
</beans>