SPRING.NET 1.3.2 学习20--方法注入之替换方法注入

这是一种用的比较少的注入方式。在Spring的配置中,通过replaced-method在需要替换类中指定需要被替换的方法,以及被哪个类替换。替换类应该实现Spring.Objects.Factory.Support中的IMethodReplacer接口。IMethodReplacer接口只有一个object Implement(object target, MethodInfo method, object[] arguments)方法。当我们调用被替换类中相应方法时,会执行Implement方法。当然,我们可以中Implement中,通过参数信息获取到相应的部分信息。

  配置如下:

 

复制代码
代码
   
   
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 >
复制代码

被替换类的代码如下:

复制代码
代码
   
   
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 }
复制代码
替换类的代码:

复制代码
代码
   
   
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 }
复制代码

使用方式:

代码
复制代码
   
   
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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值