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

来源:互联网 发布:centos7开启80端口 编辑:程序博客网 时间:2024/05/16 07:58

查询方法注入(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的类型。


原创粉丝点击