spring 引用其他Bean

2021-07-29 05:03:44 字數 2446 閱讀 5992

spring ioc 容器中定義的bean 可以相互引用,ioc 充當媒介的作用。

比如建立乙個乙個word 類,將car,people 等作為他的屬性。

public

class

world

public

car getcar()

public

void

setcar(car car)

public

people getpeople()

public

void

setpeople(people people)

public

string getgood()

public

void

setgood(string good) }

如何在配置檔案中裝配car 和people 這兩個類呢?

首先要宣告people和car這兩個bean

<

beanid=

"people"

class

= "com.modle.people"

>

<

constructor-arg

type

= "string"

index

= "0"

><

value

>

光頭牆value

>

constructor-arg

>

<

constructor-arg

type

= "string"

index

= "1"

>

<

value

>

狗熊森林

value

>

constructor-arg

>

<

constructor-arg

type

= "int"

index

= "2"

><

value

>

60value

>

constructor-arg

>

bean

>

<

beanid=

"car"

class

="com.modle.car"

>

<

property

name

="brand"

><

value

>

紅旗value

>

property

>

<

property

name

="price"

><

value

>

12value

>

property

>

bean

>

第二步:引入上面宣告的兩個bean

<

beanid=

"world"

class

= "com.modle.world"

>

<

constructor-arg

><

value

>

hello

value

>

constructor-arg

>

<

constructor-arg

><

refbean

= "car"

>

ref>

constructor-arg

>

<

constructor-arg

><

refbean

= "people"

>

ref>

constructor-arg

>

bean

>

說明:1、car的宣告用的屬性注入法

people用的建構函式注入的聯合入參法(通過引數型別和引數索引聯合匹配引數)

world的宣告使用自身反射來入參,引入bean.

2、標籤有三個屬性 分別是 bean local parent .bean是引用本容器或父容器的配置。優先引用本容器。local 是只引用本容器 。parent是只引用父容器。

spring筆記2 bean引用其他bean

在 spring筆記1 基於spring框架的第乙個程式 一文中,在spring conf.xml中配置bean時,我們向這個bean傳入了一些引數,但是這些引數都是一些簡單資料型別,如int string等,本文將說明如何將乙個bean作為乙個引數傳給另外乙個bena,即bean引用其他bean。...

Spring3 0中Bean注入其他Bean的方法

就是將想要注入的bean當成引數注入到另乙個bean中 當spring容器中只有乙個要注入型別的bean時,spring會自動將該bean注入 jdbc config.properties jdbc.driverclassname com.mysql.jdbc.driver自己開發的bean2,內部...

Spring全回顧bean之間的引用關係

首先建立乙個類 注意 此類的car屬性實際上引用了乙個carr物件,可以建立乙個car,見上篇文章 spring全回顧之構造方法注入值 package com.kk.spring.beans public class person public void setname string name pu...