• spring AOP


    AOP面向切面编程

    切面(Aspect ):一个关注点的模块化 ,这个关注点可能会横切多个对象。事务管理是J2EE应用中一个关于横切关注点的很好的例子

    通知(Advice ):在切面的某个特定的连接点上执行的动作。

    连接点(Joinpoint ):在程序执行过程中某个特定的点 ,比如某方法调用的时候或者处理异常的时候。在SpringAOP中 ,一个连接点总是表示一个方法的执行。

    切入点(Pointcut ):匹配连接点的断言。通知和一个切入点表达式关联 ,并在满足这个切入点的连接点上运行(例如,当执行某个特定名称的方法时)。切入点表达式如何和连接点匹配是AOP的核心 :Spring缺省使用AspectJ切入点语法。

    引入(Introduction ):用来给一个类型声明额外的方法或属性(也被称为连接类型声明(inter-type declaration ))。Spring允许引入新的接口(以及一个对应的实现 )到任何被代理的对象。

    <bean id="myAspect" class="test.Aspect"></bean>
        <aop:config>
            <aop:aspect ref="myAspect">
                <aop:pointcut expression="execution(* dao..*.*(..))" id="mypointcut"/>
                <!-- 前置通知  这里 mypointcut 是一个顶级切入点(<aop:config>)的id。 要定义内置切入点,可将 pointcut-ref 属性替换为 pointcut 属性-->
                <aop:before method="before" pointcut-ref="mypointcut"/>
                <!-- 后置通知,  return为返回值的参数名  afterreturn方法必须声明一个名字叫 val 的参数 -->
                <aop:after-returning method="afterreturn" pointcut-ref="mypointcut" returning="val"/>
                <!-- 异常通知 ,throwing异常的名称,获取异常,exception方法必须声明一个名字为 ex 的参数 -->
                <aop:after-throwing method="exception" pointcut-ref="mypointcut" throwing="ex"/>
                <!-- 最终通知 -->
                <aop:after method="after" pointcut-ref="mypointcut"/>
            </aop:aspect>
            
        </aop:config>
    public void afterreturn(Object val) {
            System.out.println("后置通知" +val);
        }
        public void     exception(Exception ex) {
            System.out.println("异常通知"+ ex.getClass().getName());
        }

    环绕通知(Around adivce)

    Around通知在匹配方法运行期的“周围”执行。 它有机会在目标方法的前面和后面执行,并决定什么时候运行,怎么运行,甚至是否运行。 Around通知经常在需要在一个方法执行前或后共享状态信息,并且是线程安全的情况下使用

    <aop:config>
            <aop:aspect ref="myAspect">
                <aop:pointcut expression="execution(* dao..*.*(..))" id="mypointcut"/>
                <!-- 环绕通知 -->
                <aop:around method="around" pointcut-ref="mypointcut"/>
            </aop:aspect>
        </aop:config>
    import org.aspectj.lang.ProceedingJoinPoint;
    public Object around(ProceedingJoinPoint poj) {
            Object obj=null;
            try {
                System.out.println("around前置通知");
                obj=poj.proceed();//被代理方法执行
                System.out.println("around后置通知" );
            } catch (Throwable e) {
                System.out.println("around异常通知");
            }finally{
                System.out.println("around最终通知");
            }
            return obj;
        }
  • 相关阅读:
    上周热点回顾(2.72.13)
    【故障公告】数据库服务器 CPU 100% 引发全站故障
    【故障公告】周五下午的一次突发故障
    上周热点回顾(1.171.23)
    【故障公告】k8s 开船记:增加控制舱(controlplane)造成的翻船
    [转]Flag an issue Atlassian Support / Jira Software / Resources
    [转]Create a Subtask and Link to Parent Issue in Jira
    [书目]Python数据分析实战
    jenkins
    [转]Jira ScriptRunner 插件使用总结
  • 原文地址:https://www.cnblogs.com/fudapeng/p/3863599.html
Copyright © 2020-2023  润新知