【ASP.NET】Spring.Net AOP 面向切面编程

面向切面编程

 

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);

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GreAmbWang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值