这是一种用的比较少的注入方式。在Spring的配置中,通过replaced-method在需要替换类中指定需要被替换的方法,以及被哪个类替换。替换类应该实现Spring.Objects.Factory.Support中的IMethodReplacer接口。IMethodReplacer接口只有一个object Implement(object target, MethodInfo method, object[] arguments)方法。当我们调用被替换类中相应方法时,会执行Implement方法。当然,我们可以中Implement中,通过参数信息获取到相应的部分信息。
配置如下:
![](https://i-blog.csdnimg.cn/blog_migrate/81178cc93a2a3bb5048d90d76e7ec935.gif)
1 < objects xmlns = " http://www.springframework.net " xmlns:aop = " http://www.springframework.net/aop " >
2 < object id = " parent " type = " ReplaceMethod.Parent,ReplaceMethod " >
3 < replaced - method name = " ParentMethod " replacer = " children " >
4 <!--< arg - type match = "" />-->
5 </ replaced - method >
6 < replaced - method name = " ParentMethod " replacer = " children " >
7 < arg - type match = " String " />
8 </ replaced - method >
9 </ object >
10 < object id = " children " type = " ReplaceMethod.Children,ReplaceMethod " >
11
12 </ object >
13 </ objects >
被替换类的代码如下:
![](https://i-blog.csdnimg.cn/blog_migrate/81178cc93a2a3bb5048d90d76e7ec935.gif)
1 public class Parent
2 {
3 public virtual void ParentMethod()
4 {
5 Console.WriteLine( " parent methods " );
6 }
7
8 public virtual void ParentMethod( string str)
9 {
10 Console.WriteLine( " method with parament: " + str);
11 }
12 }
![](https://i-blog.csdnimg.cn/blog_migrate/81178cc93a2a3bb5048d90d76e7ec935.gif)
1 public class Children : IMethodReplacer
2 {
3 public object Implement( object target, MethodInfo method, object [] arguments)
4 {
5 Console.WriteLine( " target type is:{0} " ,target.ToString());
6 Console.WriteLine( " method name is :{0} " ,method.Name);
7 if (arguments.Length > 0 )
8 {
9 Console.WriteLine( " the first element in artmennts is :{0} " , arguments[ 0 ].ToString());
10 }
11 return new object ();
12 }
13
14 }
使用方式:
![](https://i-blog.csdnimg.cn/blog_migrate/81178cc93a2a3bb5048d90d76e7ec935.gif)
1 static void Main( string [] args)
2 {
3 IApplicationContext context = ContextRegistry.GetContext();
4
5 Parent parent = (Parent)context.GetObject( " parent " );
6 parent.ParentMethod();
7
8 parent.ParentMethod( " test str " );
9 Console.ReadLine();
10
11 }
由此看出,Implement方法得到了执行,并覆盖重写了Parent类的ParentMethod