Spring注入的方式

2021-08-31 12:23:21 字數 1562 閱讀 5715

spring依賴注入分為兩種:建構函式注入和setter方法注入;、

1、建構函式注入的配置檔案如下:

<?xml version="1.0" encoding="utf-8"?>		

i am a learner.

helloworld.properties

在上面的這個配置檔案中我們主要有3個類:

com.openv.impl.userinfoimpl,com.openv.impl.helloworld,com.openv.impl.hellostrimpl

這三個類的構造方法分別為:

public helloworld(hellostr hstr,string words)

public hellostrimpl(string profilename)
userinfoimpl(helloworld helloworld)
從結合配置檔案和構造方法,可以看出下面幾點:1、如果構造方法中的引數型別是標準型別如字串、數字等,在配置檔案中就使用來作為輸入的引數,如果是使用者定義的類那麼久需要在配置檔案中使用來作為輸入的引數。2、如果建構函式中含有多個引數在中新增index來說明是第幾個引數,默然是從0開始的。

2、使用setter方式進行注入的配置檔案

<?xml version="1.0" encoding="utf-8"?>		

i am a learner.

helloworld.properties

同樣的我們也有三個類,名字分別為:

com.openv.impl.userinfoimpl,com.openv.impl.helloworld,com.openv.impl.hellostrimpl

這3個類中沒有顯示的構造方法,但是他們三個類有乙個共同的特點是:在這些類中都有setter方法,下面是這些類中引數的setter方法:

private string profilename;

public void setprofilename(string profilename)

public void sethstr(hellostr hstr) 

public void setwords(string words)

public void sethelloworld(helloworld helloworld)
使用setter方法我們就能通過spring的注入。在配置檔案中發生的主要變化就是變為了。

在真正開發的過程中建議使用setter方法進行注入,setter方法注入時spring開發團隊所提倡的,因為建構函式注入可能會出現下面的情況:a類依賴b類,b類依賴c類,c類又依賴a類,在使用建構函式注入時就會出現死鎖,而使用setter方法進行注入就可以有效的解決這種情況。

但是,建構函式注入存在也有他的原因,在沒有setter方法的遺留**或者沒有原始碼的第三方類時,使用是進行開發時很明智的選擇。

下面的**是我做分析的原始碼

spring注入方式

一 二 三種注入方式 1.通過set方法賦值 賦值為物件2.通過構造器賦值 3.通過p標籤賦值 當屬性值的型別相同時,常需要type來區分 注意 必須提供無參構造給bean4.自動裝配 自動尋找beanid 類的屬性值 自動尋找其他bean的型別 class 是否與該類的ref屬性型別一致 是否與該...

spring 注入方式

第一種 構造器注入 第二種 set依賴注入 bean id address class com.kuang.pojo.address property name address value 西安 property bean bean id student class com.kuang.pojo.s...

spring的依賴注入的注入方式

一 構造器注入 1 常量值 簡寫 全寫 常量 2 引用 簡寫 全寫 二 setter注入 1 常量值 簡寫 全寫 常量 2 引用 簡寫 全寫 3 陣列 沒有簡寫形式 4 列表 沒有簡寫形式 5 集合 沒有簡寫形式 6 字典 簡寫 全寫 鍵常量 值常量 7 properties 沒有簡寫形式 三 其他...