码迷,mamicode.com
首页 > 编程语言 > 详细

spring AOP

时间:2014-07-24 21:24:06      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   strong   io   for   re   

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

spring AOP,布布扣,bubuko.com

spring AOP

标签:style   blog   color   使用   strong   io   for   re   

原文地址:http://www.cnblogs.com/fudapeng/p/3863599.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!