2020国产成人精品视频,性做久久久久久久久,亚洲国产成人久久综合一区,亚洲影院天堂中文av色

分享

spring依賴注入

 路人甲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依賴注入

IOC&&DI

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方法注入

通過Setter方法注入bean的屬性值或依賴的對象,是最常用的注入方式

<!-- property來配置屬性  
name為屬性名
 value為屬性值
-->
<bean id="helloWorld" class="com.zhanghe.study.spring4.beans.helloworld.HelloWorld">
  <property name="name" value="Spring Hello"/>
</bean>
構造器注入

構造器注入需要提供相應的構造器

<!-- 可以使用index來指定參數的順序,默認是按照先后順序 -->
<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://

    本站是提供個人知識管理的網絡存儲空間,所有內容均由用戶發(fā)布,不代表本站觀點。請注意甄別內容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權內容,請點擊一鍵舉報。
    轉藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多