In the spring Ioc container, it is allowed to replace the method of another bean with the method of one 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(
"Osmanthus"
);
return
tt;
}
}
public
class
Forest {
private
Tree
tree
;
publicTree
getTree () {
Tree reTree =
new
Tree();
reTree.setName(
"willow tree"
);
return
reTree;
}
public
void
setTree(Tree tree) {
this
.
tree
= tree;
}
public
Forest () {
super
();
}
public
Forest(Tree tree) {
super
();
this
.
tree
= tree;
}
}
Arrangement one
<
bean
id
=
"forest"
class
=
"com.aowin.modle.Forest"
>
</bean>
<
bean
id
=
"forest2"
class
=
"com.aowin.modle.ForestTwo"
/>
System.
out
.println(
forest
.getTree().getName());
The output is --- willow
Arrangement two
<
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()方法去替换。