日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

spring依賴(lài)注入

 路人甲Java 2021-04-28

原文鏈接http:///2021/01/03/%E6%A1%86%E6%9E%B6/spring/spring%E4%BE%9D%E8%B5%96%E6%B3%A8%E5%85%A5/

spring依賴(lài)注入

IOC&&DI

IOC(Inversion of Control)一般分為兩種類(lèi)型:依賴(lài)注入DI(Dependency Injection)和依賴(lài)查找(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依賴(lài)注入是IOC的一個(gè)方面,不需要?jiǎng)?chuàng)建對(duì)象,只需描述如何被創(chuàng)建,在配置文件中描述組件需要哪些服務(wù),之后IOC容器進(jìn)行組裝

IOC的注入方式:1、構(gòu)造器依賴(lài)注入 2、Setter方法注入 3、工廠方法注入(很少使用)

Setter方法注入

通過(guò)Setter方法注入bean的屬性值或依賴(lài)的對(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)行精確匹配,還需要使用類(lèi)型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://

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買(mǎi)等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類(lèi)似文章 更多