SpringIOC使用擴充套件

2022-04-05 05:32:41 字數 4125 閱讀 2801

在上篇部落格中,我們使用spring通過setter訪問器實現了對屬性的賦值,這種做法被稱為設值注入。除此之外spring還提供了通過構造方法賦值的能力,成為構造注入。下面我們通過乙個小demo來了解如何通過構造方法來注入值(因乙個類中可能包含其他自定義型別的物件,所以我們採用student類中包含car類的例項來演示如何通過構造來給student類屬性注入值)

student類:

public

class

student

//建構函式

public

student(string name, integer age, car car)

public

student()

//屬性訪問器

public

string getname()

public

void

setname(string name)

public

integer getage()

public

void

setage(integer age)

public

car getcar()

public

void

setcar(car car)

}

car類:

public

class

car

public

void

setcolor(string color)

//重寫tostring()方法方便測試

@override

public

string tostring()

}

<

bean

id="car"

class

="cn.wz.entity.car"

>

<

property

name

="color"

value

="白色"

/>

bean

>

<

bean

id="stu"

class

="cn.wz.entity.student"

>

<

constructor-arg

index

="0"

value

="王哲"

/>

<

constructor-arg

index

="1"

value

="18"

/>

<

constructor-arg

index

="2"

ref="car"

/>

bean

>

測試**:

public

class

test

public

static

void

hasargumentconstructor()

}

最終執行結果:

spring配置檔案採用schema形式,使用不同的名命空間管理不同型別的配置,是的配置檔案更具擴充套件性。而p命名空間的配置則不再使用property子元素來為物件的屬性注入值,而是以bean元素屬性的方式來注入值如我們將上面demo的配置**更改如下:

<

bean

id="car"

class

="cn.wz.entity.car"

>

<

property

name

="color"

value

="白色"

/>

bean

>

<

bean

id="stu"

class

="cn.wz.entity.student"

p:name

="王哲"

p:age

="18"

p:car-ref

="car"

/>

其測試用例執行效果是一樣的,但需要注意的是在使用這種方式給屬性注入值時一定要先導入p命名空間如圖所示:

從上圖中我們可以發現我們再xml配置檔案的標頭檔案中不但配置了p命名空間還有c命名空間,c命名空間是在使用構造注入值時使用其用法和p命名空間一樣,這裡不再進行演示了。

對於存在屬性型別為集合的物件spring提供了list、set、map等元素對其進行配置。具體配置如下:

<

bean

id="list"

class

="cn.wz.entity.student"

>

<

property

name

="list"

>

<

list

>

<

value

>王哲

value

>

<

value

>張一銘

value

>

list

>

property

>

bean

>

<

bean

id="set"

class

="cn.wz.entity.student"

>

<

property

name

="set"

>

<

set>

<

value

>王哲

value

>

<

value

>張一銘

value

>

set>

property

>

bean

>

<

bean

id="map"

class

="cn.wz.entity.student"

>

<

property

name

="map"

>

<

map>

<

entry

key="wz"

><

value

>王哲

value

>

entry

>

<

entry

key="zym"

>

<

value

>張一銘

value

>

entry

>

map>

property

>

bean

>

<

bean

id="array"

class

="cn.wz.entity.student"

>

<

property

name

="array"

>

<

list

>

<

value

>王哲

value

>

<

value

>張一銘

value

>

list

>

property

>

bean

>

spring IOC容器的擴充套件

在此之前已經完成了ioc對 xml的解析和例項化工作,接下來需要分析 spring 的高階版本對 ioc容器的功能擴充套件 分析如下 synchronized this.startupshutdownmonitor 接下來,即開始對上面的步奏進行一一的講解 preparerefresh 準備重新整理...

spring IOC 使用註解方式配置

spring 基於註解的方式ioc操作bean管理 1 配置m en依賴 org.springframework spring webmvc 5.2.9.release junit junit 4.13 test org.projectlombok lombok 1.18.20 2 xml檔案配置 ...

Spring IOC和工廠模式聯合使用簡化工廠模式

目錄 1 應用場景 2 傳統工廠模式 3 傳統工廠模式實現1中應用場景的弊端 4 ioc和工廠模式連合使用實現1中描述的場景 1 應用場景 在mypm的工作流業務中,有三種業務對像可以走工作流,分別為 文件,專案和工作任務 這三種業務對像在走工作流時,具體處理業務是有差別的,工作流引擎要根據不同的業...