在spring Ioc 容器里,允许用一个Bean 的方法去替换另一个Bean 的方法。
public
class
ForestTwo
implements
MethodReplacer {
public
ForestTwo() {
super
();
}
public
Object reimplement(Object arg0, Method arg1, Object[] arg2)
throws
Throwable {
Tree tt =
new
Tree();
tt.setName(
"桂花"
);
return
tt;
}
}
public
class
Forest {
private
Tree
tree
;
public
Tree getTree() {
Tree reTree =
new
Tree();
reTree.setName(
"柳树"
);
return
reTree;
}
public
void
setTree(Tree tree) {
this
.
tree
= tree;
}
public
Forest() {
super
();
}
public
Forest(Tree tree) {
super
();
this
.
tree
= tree;
}
}
配置一
<
bean
id
=
"forest"
class
=
"com.aowin.modle.Forest"
>
</
bean
>
<
bean
id
=
"forest2"
class
=
"com.aowin.modle.ForestTwo"
/>
System.
out
.println(
forest
.getTree().getName());
输出的是---柳树
配置二
<
bean
id
=
"forest"
class
=
"com.aowin.modle.Forest"
>
<
replaced-method
name
=
"getTree"
replacer
=
"forest2"
></
replaced-method
>
</
bean
>
<
bean
id
=
"forest2"
class
=
"com.aowin.modle.ForestTwo"
/>
System.
out
.println(
forest
.getTree().getName());
输出的是 桂花。
用于替换他人的Bean必须实现
MethodReplacer接口
因为
forest2 实现了
MethodReplacer 接口,重写了该接口下的
reimplement()方法。
当
forest 调用getTree方法时,就会被
forest2替换掉,用
重写了的
reimplement()方法去替换。