面向切面编程
https://wenku.baidu.com/view/973f6abc453610661ed9f4b5.html
应用
调用每个方法之前或之后,执行其它方法
添加dll
Common.Logging.dll
Spring.Aop.dll
Spring.Core.dll
编写服务接口
public interface IUserInfoService
{
int Add(int a, int b);
}
实现接口
public class UserInfoService : IUserInfoService
{
public int Add(int a, int b)
{
return a + b;
}
}
添加环绕通知
/// <summary>
/// 日志环绕通知
/// </summary>
public class LoggingAroundAdvice : IMethodInterceptor
{
public object Invoke(IMethodInvocation invocation)
{
Console.Out.WriteLine("执行前");
object resValue = invocation.Proceed();
Console.Out.WriteLine("执行后,返回值:" + resValue);
return resValue;
}
}
添加配置
<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">
<!--配置环绕通知-->
<object id="LoggingAroundAdvice" type="AOPDemo.LoggingAroundAdvice, AOPDemo"></object>
<object id="UserInfoService" type="Spring.Aop.Framework.ProxyFactoryObject">
<property name="Target">
<object id="myServiceObjectTarget" type="AOPDemo.UserInfoService,AOPDemo"></object>
</property>
<property name="InterceptorNames">
<list>
<value>LoggingAroundAdvice</value>
</list>
</property>
</object>
</objects>
</spring>
实现
//传统的实现方法
//IUserInfoService userInfoService = new UserInfoService();
//int res = userInfoService.Add(2, 4);
//使用Spring.Net AOP 实现
IApplicationContext ctx = ContextRegistry.GetContext();
//请求定义的对象
IUserInfoService userInfoService = (IUserInfoService)ctx.GetObject("UserInfoService");
userInfoService.Add(2, 4);