原文鏈接http://zhhll.icu/2021/%E6%A1%86%E6%9E%B6/spring/spring%E4%BE%9D%E8%B5%96%E6%B3%A8%E5%85%A5/
spring依賴注入
IOC&&DI
IOC(Inversion of Control)一般分為兩種類型:依賴注入DI(Dependency Injection)和依賴查找(Dependency Lookup)
org.springframework.beans.factory.BeanFactory是IOC容器的具體實(shí)現(xiàn),是Spring IOC容器的核心接口
Spring IOC負(fù)責(zé)創(chuàng)建對(duì)象则北,管理對(duì)象萍膛,裝配對(duì)象改化,配置對(duì)象鸠信,并且管理這些對(duì)象的整個(gè)生命周期嵌巷。
優(yōu)點(diǎn):把應(yīng)用的代碼量降到最低衣屏。最小代價(jià)和最小侵入式是松散耦合得以實(shí)現(xiàn)施绎。IOC容器支持加載服務(wù)時(shí)的餓漢式初始化和懶加載
DI依賴注入是IOC的一個(gè)方面耕赘,不需要?jiǎng)?chuàng)建對(duì)象骄蝇,只需描述如何被創(chuàng)建,在配置文件中描述組件需要哪些服務(wù)操骡,之后IOC容器進(jìn)行組裝
IOC的注入方式:1九火、構(gòu)造器依賴注入 2、Setter方法注入 3当娱、工廠方法注入(很少使用)
Setter方法注入
通過(guò)Setter方法注入bean的屬性值或依賴的對(duì)象,是最常用的注入方式
<!-- property來(lái)配置屬性
name為屬性名
value為屬性值
-->
<bean id="helloWorld" class="com.zhanghe.study.spring4.beans.helloworld.HelloWorld">
<property name="name" value="Spring Hello"/>
</bean>
構(gòu)造器注入
構(gòu)造器注入需要提供相應(yīng)的構(gòu)造器
<!-- 可以使用index來(lái)指定參數(shù)的順序吃既,默認(rèn)是按照先后順序 -->
<bean id="car" class="com.zhanghe.study.spring4.beans.beantest.Car">
<constructor-arg value="法拉利" index="0"/>
<constructor-arg value="200" index="1"/>
</bean>
但是如果存在重載的構(gòu)造器的話,只使用index索引方式無(wú)法進(jìn)行精確匹配跨细,還需要使用類型type來(lái)進(jìn)行區(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>
由于本身的博客百度沒(méi)有收錄,博客地址http://zhhll.icu