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动态切入点,需要自定义

先到此为止

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

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

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 常见电容的种类_电容工作原理

    常见电容的种类_电容工作原理一、瓷介电容器(CC)1.结构用陶瓷材料作介质,在陶瓷表面涂覆一层金属(银)薄膜,再经高温烧结后作为电极而成。瓷介电容器又分1类电介质(NPO、CCG));2类电介质(X7R、2X1)和3类电介质(Y5V、2F4)瓷介电容器。2.特点1类瓷介电容器具有温度系数小、稳定性高、损耗低、耐压高等优点。最大容量不超过1000pF,常用的有CC1、CC2、CC18A、CC11、…

    2022年8月22日
    9
  • 常见分布式id生成方案_分布式id生成方案

    常见分布式id生成方案_分布式id生成方案文章目录一、为什么要用分布式ID1、什么是分布式ID2、那么分布式ID需要满足哪些条件二、分布式ID有哪些生成方式1、基于UUID2、基于数据库自增ID3、基于数据库集群模式4、基于数据库的号段模式5、基于Redis模式6、基于雪花算法(Snowflake)模式7、百度(uid-generator)8、美团(Leaf)号段模式snowflake模式9、滴滴(Tinyid)Http方式接入Java客户端方式接入三、总结一、为什么要用分布式ID在说分布式ID的具体实现之前,我们来简单分析一下为什么用分布式

    2025年7月28日
    7
  • 函数WSAStartup[通俗易懂]

    函数WSAStartup一、WSAStartup函数               intWSAStartup                      (                         WORDwVersionRequested,                         LPWSADATAlpWSAData                      

    2022年4月7日
    118
  • 关于Android多按钮切换的例子!

    关于Android多按钮切换的例子!

    2022年3月12日
    42
  • Linux的EXPORT_SYMBOL和EXPORT_SYMBOL_GPL的使用和区别

    Linux的EXPORT_SYMBOL和EXPORT_SYMBOL_GPL的使用和区别简要说明使用方法:一个模块mod1中定义一个函数func1;在另外一个模块mod2中定义一个函数func2,func2调用func1。在模块mod1中,EXPORT_SYMBOL(func1);在模块mod2中,externintfunc1();就可以在mod2中调用func1了。同理EXPORT_SYMBOL_GPL使用相同。1、EXPORT_SYMBOL的作用是什么?EXPO…

    2022年7月12日
    31
  • Activiti流程引擎_activiti工作流原理

    Activiti流程引擎_activiti工作流原理Activiti框架提供的流程引擎配置类ProcessEngineConfiguration的类图如下:下面的图是流程引擎的架构图:由上图我们可以很清楚地从全局角度了解ProcessEngineConfiguration类:1)EngineServices:该接口中定义了获取各种服务类实例对象的方法。2)ProcessEngine:继承EngineServices接口,并增…

    2022年10月20日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

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