原文鏈接http://zhhll.icu/2021/01/03/%E6%A1%86%E6%9E%B6/spring/spring%E4%BE%9D%E8%B5%96%E6%B3%A8%E5%85%A5/
IOC(Inversion of Control)一般分為兩種類型:依賴注入DI(Dependency Injection)和依賴查找(Dependency Lookup)
org.springframework.beans.factory.BeanFactory是IOC容器的具體實現(xiàn),是Spring IOC容器的核心接口
Spring IOC負責創(chuàng)建對象,管理對象,裝配對象,配置對象,并且管理這些對象的整個生命周期。
優(yōu)點:把應用的代碼量降到最低。最小代價和最小侵入式是松散耦合得以實現(xiàn)。IOC容器支持加載服務時的餓漢式初始化和懶加載
DI依賴注入是IOC的一個方面,不需要創(chuàng)建對象,只需描述如何被創(chuàng)建,在配置文件中描述組件需要哪些服務,之后IOC容器進行組裝
IOC的注入方式:1、構造器依賴注入 2、Setter方法注入 3、工廠方法注入(很少使用)
通過Setter方法注入bean的屬性值或依賴的對象,是最常用的注入方式
<!-- property來配置屬性
name為屬性名
value為屬性值
-->
<bean id="helloWorld" class="com.zhanghe.study.spring4.beans.helloworld.HelloWorld">
<property name="name" value="Spring Hello"/>
</bean>
構造器注入需要提供相應的構造器
<!-- 可以使用index來指定參數(shù)的順序,默認是按照先后順序 -->
<bean id="car" class="com.zhanghe.study.spring4.beans.beantest.Car">
<constructor-arg value="法拉利" index="0"/>
<constructor-arg value="200" index="1"/>
</bean>
但是如果存在重載的構造器的話,只使用index索引方式無法進行精確匹配,還需要使用類型type來進行區(qū)分,index和type可以搭配使用
public Car(String brand, double price) {
this.brand = brand;
this.price = price;
}
public Car(String brand, int speed) {
this.brand = brand;
this.speed = speed;
}
<bean id="car" class="com.zhanghe.study.spring4.beans.beantest.Car">
<constructor-arg value="法拉利" index="0"/>
<constructor-arg value="20000.0" type="double"/>
</bean>
<bean id="car2" class="com.zhanghe.study.spring4.beans.beantest.Car">
<constructor-arg value="瑪莎拉蒂" index="0"/>
<constructor-arg value="250" type="int"/>
</bean>
由于本身的博客百度沒有收錄,博客地址http://zhhll.icu