spring ioc 容器中定义的Bean 可以相互引用,Ioc 充当媒介的作用。
比如创建一个一个word 类,将Car,People 等作为他的属性。
public
class
World {
private
Car
car
;
private
People
people
;
private
String
good
;
public
World(Car car, People people, String good) {
super
();
this
.
car
= car;
this
.
people
= people;
this
.
good
= good;
}
public
Car getCar() {
return
car
;
}
public
void
setCar(Car car) {
this
.
car
= car;
}
public
People getPeople() {
return
people
;
}
public
void
setPeople(People people) {
this
.
people
= people;
}
public
String getGood() {
return
good
;
}
public
void
setGood(String good) {
this
.
good
= good;
}
}
如何在配置文件中装配Car 和People 这两个类呢?
首先要声明People和Car这两个Bean
<!-- 构造函数中的 联合入参方法 -->
<
bean
id
=
"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
>
60
</
value
></
constructor-arg
>
</
bean
>
<!-- 属性注入方法 -->
<
bean
id
=
"car"
class
=
"com.modle.Car"
>
<
property
name
=
"brand"
><
value
>
红旗
</
value
></
property
>
<
property
name
=
"price"
><
value
>
12
</
value
></
property
>
</
bean
>
第二步:引入上面声明的两个Bean
<!--构造函数注入 通过自身反射入参 -->
<
bean
id
=
"world"
class
=
"com.modle.World"
>
<
constructor-arg
><
value
>
hello
</
value
></
constructor-arg
>
<
constructor-arg
><
ref
bean
=
"car"
></
ref
></
constructor-arg
>
<!-- 注入上面的bean -->
<
constructor-arg
><
ref
bean
=
"people"
></
ref
></
constructor-arg
>
</
bean
>
说明:1、Car的声明用的属性注入法
People用的构造函数注入的联合入参法(通过参数类型和参数索引联合匹配参数)
World的声明使用自身反射来入参,引入Bean.
2、<ref>标签有三个属性 分别是 bean local parent .bean是引用本容器或父容器的配置。优先引用本容器。local 是只引用本容器 。parent是只引用父容器。