Spring.NET学习笔记(6)-基础AOP

Spring.NET学习笔记(6)-基础AOP

   

1.在我们的系统中,常常要对操作进行记录,比如说某某人新增了一笔数据,然后在数据库中增加一笔操作记录

2.前端开发人员往往会在ajax调用后端的时候,调用之前先做一些数据检验的工作,调用之后对于返回的数据ui做出一些反应

3.后端开发人员有时候会做一个数据的ing和ed事件操作,比如插入数据,InsertIng和Inserted事件.

以上的种种反应在进行一个方法的操作,往往还有着其他的关联,这被我们称之为耦合,系统越大,关联越多。再比如添加日志这个功能,某天就不要了,但添加日志的代码与新增数据的代码是写在一起的,这时候就必须做出修改。

对于这些问题,我们就可以用AOP来解决。关于AOP有很多概念,我们直接看代码,不多概念。

1.通知

(1)前后通知和抛错通知,以接口来实现

public class ConsoleLoggingBeforeAdvice : IMethodBeforeAdvice
{
    public void Before(MethodInfo method, object[] args, object target)
    {
        Console.Out.WriteLine("Intercepted call to this method : " + method.Name);
        Console.Out.WriteLine("    The target is       : " + target);
        Console.Out.WriteLine("    The arguments are   : ");
        if(args != null)
        {
            foreach (object arg in args)
            {
                Console.Out.WriteLine("\t: " + arg);
            }
        }
    }
}


public class ConsoleLoggingAfterAdvice : IAfterReturningAdvice
{
    public void AfterReturning(
        object returnValue, MethodInfo method, object[] args, object target)
    {
        Console.Out.WriteLine("This method call returned successfully : " + method.Name);
        Console.Out.WriteLine("    The target was      : " + target);
        Console.Out.WriteLine("    The arguments were  : ");
        if (args != null)
        {
            foreach (object arg in args)
            {
                Console.Out.WriteLine("\t: " + arg);
            }
        }
        Console.Out.WriteLine("    The return value is : " + returnValue);
    }
}


public class ConsoleLoggingThrowsAdvice : IThrowsAdvice
{
    public void AfterThrowing(Exception ex)
    {
        Console.Error.WriteLine(
            String.Format("Advised method threw this exception : {0}", ex.Message));
    }
}

执行每个方法时都会触发通知,注意当设置属性的时候也会触发(因为属性是伪方法)

// Create AOP proxy programmatically.
ProxyFactory factory = new ProxyFactory(new ServiceCommand());
factory.AddAdvice(new ConsoleLoggingBeforeAdvice());
factory.AddAdvice(new ConsoleLoggingAfterAdvice());
factory.AddAdvice(new ConsoleLoggingThrowsAdvice());
ICommand command = (ICommand)factory.GetProxy();

command.Execute();

(2)环绕通知

即以上三个通知的集合,还可以充当拦截器的作用,阻止方法触发

public class ConsoleLoggingAroundAdvice : IMethodInterceptor
{
    public object Invoke(IMethodInvocation invocation)
    {
        Console.Out.WriteLine(String.Format(
            "Intercepted call : about to invoke method '{0}'", invocation.Method.Name));

        object returnValue = invocation.Proceed();

        Console.Out.WriteLine(String.Format(
            "Intercepted call : returned '{0}'", returnValue));

        return returnValue;
    }
}

 

ProxyFactory factory = new ProxyFactory(new ServiceCommand());
              
factory.AddAdvice(new ConsoleLoggingAroundAdvice());

ICommand command = (ICommand)factory.GetProxy();

command.Execute();
if (command.IsUndoCapable)
{
    command.UnExecute();
}

 

2.以配置文件方式配置

<object id="aroundAdvice" 
        type="Spring.AopQuickStart.Aspects.ConsoleLoggingAroundAdvice, Spring.AopQuickStart.Common" />
<object id="throwsAdvice" 
        type="Spring.AopQuickStart.Aspects.ConsoleLoggingThrowsAdvice, Spring.AopQuickStart.Common" />

<object id="myServiceCommand" type="Spring.Aop.Framework.ProxyFactoryObject">
  <property name="Target">
    <object type="Spring.AopQuickStart.Commands.ServiceCommand, Spring.AopQuickStart.Common" />
  </property>
  <property name="InterceptorNames">
    <list>
      <value>aroundAdvice</value>
      <value>throwsAdvice</value>
    </list>
  </property>
</object>

3.切入点

即通知在何时(指在某个方法)执行,以上通知是不管调用什么属性和方法都通知,显然我们就需要某几个方法同志就好了,所以需要一个方法匹配的过滤,如下代码NameMatchMethodPointcutAdvisor可进行方法名字过滤,

<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="throwsAdvice" 
              type="Spring.AopQuickStart.Aspects.ConsoleLoggingThrowsAdvice, Spring.AopQuickStart.Common" />

      <object id="myServiceCommand" type="Spring.Aop.Framework.ProxyFactoryObject">
        <property name="Target">
          <object type="Spring.AopQuickStart.Commands.ServiceCommand, Spring.AopQuickStart.Common" />
        </property>
        <property name="InterceptorNames">
          <list>
            <value>aroundAdvisor</value>
            <value>throwsAdvice</value>
          </list>
        </property>
      </object>


除了此过滤器,只要实现IPointcutAdvisor接口的都可以,spring还提供了其他的过滤类。

1.RegularExpressionMethodPointcutAdvisor  &&  SdkRegularExpressionMethodPointcut

正则表达式匹配

<object id="settersAndAbsquatulatePointcut"
    type="Spring.Aop.Support.SdkRegularExpressionMethodPointcut, Spring.Aop">
  <property name="patterns">
    <list>
      <value>.*set.*</value>
      <value>.*absquatulate</value>
    </list>
  </property>
</object>


<object id="settersAndAbsquatulateAdvisor"
    type="Spring.Aop.Support.RegularExpressionMethodPointcutAdvisor, Spring.Aop">
  <property name="advice">
    <ref local="objectNameOfAopAllianceInterceptor"/>
  </property>
  <property name="patterns">
    <list>
      <value>.*set.*</value>
      <value>.*absquatulate</value>
    </list>
  </property>
</object>


2.AttributeMatchMethodPointcutAdvisor

在方法上挂标签匹配

<object id="aroundAdvisor" type="Spring.Aop.Support.AttributeMatchMethodPointcutAdvisor, Spring.Aop">
  <property name="Advice">
    <object type="Spring.AopQuickStart.Aspects.ConsoleLoggingAdvice, Spring.AopQuickStart.Step4" />
  </property>
  <property name="Attribute" 
            value="Spring.AopQuickStart.Attributes.ConsoleLoggingAttribute, Spring.AopQuickStart.Step4" />
</object>


3.DynamicMethodMatcherPointcutAdvisor动态切入点,需要自定义

先到此为止

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/110870.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • 原型模式的应用场景_原型模式深浅克隆区别

    原型模式的应用场景_原型模式深浅克隆区别ProtoType 原型模式动机模型定义实例结构要点总结笔记动机在软件系统中,经常面临着”某些结构复杂的对象“的创建工作;由于需求的变化,这些对象经常面临着剧烈的变化,但是它们却拥有比较稳定一致的接口如何应对这种变化?如何向”客户程序“(使用这些对象的程序)”隔离出“这些易变对象,从而使得”依赖这些易变对象的客户程序“不随着需求变化而变化?模型定义使用原型实例指定创建对象的种类,然后通过拷贝这些原型来创建新对象。实例和工厂模型用的同一个实例工厂模式//工厂class SplitterF

  • win10 ipconfig flushdns 清除DNS缓存,修复上网问题

    win10 ipconfig flushdns 清除DNS缓存,修复上网问题win10ipconfigflushdns清除DNS缓存,修复上网问题
    一、使用ipconfig/flushdns命令刷新DNS解析缓存
    1、右键点击系统桌面左下角的【开始】,在开始的右键

  • pycharm快捷键和常规设置[通俗易懂]

    pycharm快捷键和常规设置[通俗易懂]记录下我常用的pycharm快捷键和设置(Windows10)1、更换背景:文件—设置—-外观与行为—外观—背景图像本来是没想到设置背景图像的。脑子一抽换了一个,感觉发现了新大陆。(程序员鼓励师)2、列模式Alt+Shift+鼠标左键可以批量选中并修改3、Ctrl+E打开最近文件。多用于打开了多个文件时快速定位。也可以在tab标签里找,不过tab打开多了就会挤压之前标签,看起来特别费劲。4、Ctrl+B快速定位变量在哪定义的快速定位函数定义代码5、Shift+Enter

  • win732位系统怎么安装_windows7可以安装python 什么版本

    win732位系统怎么安装_windows7可以安装python 什么版本win732位系统如何安装pycharm?1.查找安装说明百度找到了PyCharm安装教程(Windows),地址是:https://www.runoob.com/w3cnote/pycharm-windows-install.html按照步骤选择了community社区版的pycharm进行下载安装安装过程中出现如下提示信息:提示信息显示安装pycharm2019.3.1版本…

  • SpringBoot热部署(IDEA 2109 )「建议收藏」

    SpringBoot热部署(IDEA 2109 )「建议收藏」SpringBoot热部署(IDEA 2109 )

  • java中数组怎么定义_java中数组的定义

    java中数组怎么定义_java中数组的定义展开全部数组的定义语法有两种:typearrayName[];type[]arrayName;type为Java中的任意数据类62616964757a686964616fe58685e5aeb931333365646364型,包括基本类型和组合类型,arrayName为数组名,必须是一个合法的标识符,[]指明该变量是一个数组类型变量。/***数组的三种定义方法**1.数组类型[]数…

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号