SPRING.NET 1.3.2 学习19--方法注入之查询方法注入

查询方法注入(Lookup Method Injection),对这个名称一直都感到奇怪,特别是了解了它的用法以后,感觉它就像是抽像工厂?查询方法XML配置的lookup-method name中配置的方法名,一定会返回object中配置的对象

Spring.Net可以对动态的对目标对象的抽象方法或者虚方法进行覆盖,并且可以在容器类查找已命名的对象,查询方法注入就利用了这一功能。被查询的对象一般应该是非Singleton的,但是也可以是Singleton的。Spring.NET使用System.Reflecttion.Emit命名空间中的类型在运行时动态生成某个类的子类并覆盖其方法,以实现查询方法注入。被注入的方法应该是抽象无参数的或者虚方法,并且方法的可见性应该在Private以上(因为抽象方法或者虚方法设置为private就没有意义)。

配置方式如下:

复制代码
代码
   
   
1 < objects xmlns = " http://www.springframework.net " xmlns:aop = " http://www.springframework.net/aop " >
2 < object id = " parent " type = " lookUpMethod.Parent,lookUpMethod " singleton = " false " >
3 < lookup - method name = " CreateInstance " object = " children " />
4
5 </ object >
6
7 < object id = " children " type = " lookUpMethod.Children,lookUpMethod " >
8
9 </ object >
10 </ objects >
复制代码

类代码:

 

复制代码
代码
   
   
1 public abstract class Parent
2 {
3 // public abstract Children CreateInstance();
4  
5 public virtual Children CreateInstance()
6 {
7 return null ;
8 }
9 }
10 public class Children
11 {
12 public void TestMethod()
13 {
14 Console.WriteLine( " Chileren method " );
15
16 }
17 }
复制代码

使用方式:

 

代码
复制代码
   
   
1 static void Main( string [] args)
2 {
3 IApplicationContext context = ContextRegistry.GetContext();
4
5 Parent parent = (Parent)context.GetObject( " parent " );
6 Console.WriteLine(parent.CreateInstance().ToString());
7 parent.CreateInstance().TestMethod();
8 Console.ReadLine();
9
10 }
复制代码

结果如下图:

 

由运行的结果我们可以看出:调用parent的抽象方法CreateInstance时,实际上返回了children的类型。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值