1、新建库AOPCommon,里面定义一个接口ICommand:
namespace AOPTest.BLL
{
public interface ICommand
{
void Execute();
void UnExecute();
}
}
2、新建库AOPBLL,引用AOPCommon,定义一个类实现ICommand接口:
namespace AOPTest.BLL
{
public class Command : ICommand
{
public void Execute()
{
Console.Out.WriteLine("Command.Execute");
}
public void UnExecute()
{
Console.Out.WriteLine("Command.UnExecute");
}
}
}
3、新建库AOPInteceptor,引用Spring.Core.dll和Spring.Aop.dll,其中定义方法拦截类:
namespace AOPCommon.Aspects
{
class Interceptor : IMethodInterceptor
{
public object Invoke(IMethodInvocation invocation)
{
//todo before invoke method
Console.Out.WriteLine("before invoke method");
object result = invocation.Proceed();
//todo after invoke method
Console.Out.WriteLine("after invoke method");
return result;
}
}
}
注:可分别实现IAfterReturningAdvice(函数调用返回后触发)、IMethodInterceptor(方法调用前后都可进行相关处理)、IMethodBeforeAdvice(函数调用前触发)、IThrowsAdvice(函数发生异常时触发)接口,在函数相应阶段进行拦截处理。
4、新建一个控制台程序,引用AOPCommon,Spring.Core.dll,Spring.AOP.dll,在Program.cs中添加代码:
class Program
{
static void Main(string[] args)
{
IApplicationContext ctx = ContextRegistry.GetContext();
ICommand command = (ICommand)ctx["myCommand"];
command.Execute();
Console.Read();
}
}
修改app.config配置文件,注册aop方法拦截信息:
?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core" />
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
</sectionGroup>
</configSections>
<spring>
<context>
<resource uri="config://spring/objects" />
</context>
<objects xmlns="http://www.springframework.net">
<description>这是一个阐述AOP功能的范例</description>
<!-- 注册方面拦截类 -->
<object id="aroundAdvice" type="AOPCommon.Aspects.Interceptor, AOPInterceptor" />
<!--
拦截方法类可以根据方法名称判断是否需要拦截:
<object id="aroundAdvisor" type="Spring.Aop.Support.NameMatchMethodPointcutAdvisor, Spring.Aop">
<property name="Advice">
<object type="Spring.AopQuickStart.Aspects.ConsoleLoggingAroundAdvice, Spring.AopQuickStart.Common" />
</property>
<property name="MappedNames">
<list>
<value>*Execute</value>
</list>
</property>
</object>
-->
<!-- 定义业务对象的代理类-->
<object id="myCommand" type="Spring.Aop.Framework.ProxyFactoryObject">
<property name="Target">
<!--指定代理类目标对象,即实际的业务对象-->
<object type="AOPTest.BLL.Command, AOPBLL" />
</property>
<!--指定方法拦截对象-->
<property name="InterceptorNames">
<list>
<value>aroundAdvice</value>
</list>
</property>
</object>
</objects>
</spring>
</configuration>
总结:使用AOP可以方便的对应用程序进行扩展。对于可能频繁变动的业务逻辑,定义接口后,在一个单独dll中实现,通过配置附加到应用程序中,由Spring动态加载dll;并可对业务方法进行拦截,实现额外处理。
注意:应用程序并不知道业务dll和方法拦截dll的存在,完全由配置文件指定,可以方便的调整业务逻辑。