学习Spring框架系列(三):AOP 详解


  • AOP的英文解释——AOPAspect Oriented Programming面向切面编程。主要目的是通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态统一添加功能的一种技术。

     

    反射机制剖析(三): 谈谈代理模式是如何体现反射的中谈到记录程序运行日志,代码存在冗余和开放修改的问题,最终采用JDK动态代理封装日志操作。其实这就是AOP的应用,除此之外,使用CGLIB动态代理也可达到相同的目的。

    今天主要通过实际应用进一步熟悉AOP

     

    通过AOP来解决下面的需求:

    1. 对部分函数的调用进行日志记录,用于观察特定问题在运行过程中的函数调用情况
    1. 监控部分重要函数,若抛出指定的异常,需要以短信或邮件方式通知相关人员
    1. 金控部分重要函数的执行时间

     

    切面类TestAspect

    package com.spring.aop;
     
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.ProceedingJoinPoint;
     
    /*
     * 切面
     */
    public class TestAspect {
    public void doAfter(JoinPoint jp) { 
            System.out.println("log Ending method: " 
                    + jp.getTarget().getClass().getName() + "." 
                    + jp.getSignature().getName()); 
        } 
     
        public Object doAround(ProceedingJoinPoint pjp) throws Throwable { 
            long time = System.currentTimeMillis(); 
            Object retVal = pjp.proceed(); 
            time = System.currentTimeMillis() - time; 
            System.out.println("process time: " + time + " ms"); 
            return retVal; 
        } 
     
        public void doBefore(JoinPoint jp) { 
            System.out.println("log Begining method: " 
                    + jp.getTarget().getClass().getName() + "." 
                    + jp.getSignature().getName()); 
        } 
     
        public void doThrowing(JoinPoint jp, Throwable ex) { 
            System.out.println("method " + jp.getTarget().getClass().getName() 
                    + "." + jp.getSignature().getName() + " throw exception"); 
            System.out.println(ex.getMessage()); 
        } 
     
        private void sendEx(String ex) { 
            //TODO 发送短信或邮件提醒 
        } 
    }


     

    service层

    package com.spring.service;
     
    /*
     * 接口A
     */
    public interface AService {
     
     public void fooA(String _msg); 
     
     public void barA(); 
    }
     
    package com.spring.service;
     
    /**
     *接口A的实现类
     */ 
    public class AServiceImpl implements AService { 
     
        public void barA() { 
            System.out.println("AServiceImpl.barA()"); 
        } 
     
        public void fooA(String _msg) { 
            System.out.println("AServiceImpl.fooA(msg:"+_msg+")"); 
        } 
    }


     

    package com.spring.service;
     
    /**
     * Service类B
     * @author TCH
     *
     */
    public class BServiceImpl {
     
     public void barB(String _msg, int _type) { 
            System.out.println("BServiceImpl.barB(msg:"+_msg+" type:"+_type+")"); 
            if(_type == 1) 
                throw new IllegalArgumentException("测试异常"); 
        } 
     
        public void fooB() { 
            System.out.println("BServiceImpl.fooB()"); 
        } 
    }


     

    ApplicationContext

    <?xml version="1.0" encoding="UTF-8"?>
     
    <beans xmlns="http://www.springframework.org/schema/beans"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:aop="http://www.springframework.org/schema/aop"
         xmlns:tx="http://www.springframework.org/schema/tx"
         xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
               http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
               http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
     
    <aop:config> 
            <aop:aspect id="TestAspect" ref="aspectBean"> 
                <!--配置com.spring.service包下所有类或接口的所有方法--> 
                <aop:pointcut id="businessService" 
                    expression="execution(* com.spring.service.*.*(..))" /> 
                <aop:before pointcut-ref="businessService" method="doBefore"/> 
                <aop:after pointcut-ref="businessService" method="doAfter"/> 
                <aop:around pointcut-ref="businessService" method="doAround"/> 
                <aop:after-throwing pointcut-ref="businessService" method="doThrowing" throwing="ex"/> 
            </aop:aspect> 
        </aop:config> 
         
        <bean id="aspectBean" class="com.spring.aop.TestAspect" /> 
        <bean id="aService" class="com.spring.service.AServiceImpl"></bean> 
        <bean id="bService" class="com.spring.service.BServiceImpl"></bean>
    </beans>


     

     

    测试类AOPTest

    package com.spring.service;
     
    import junit.framework.TestCase;
     
     
     
    public class AOPTest extends TestCase {
     
    private AService aService; 
       
        private BServiceImpl bService; 
         
         
        /**
         * 测试正常调用
         */ 
        public void testCall() 
        { 
            System.out.println("SpringTest JUnit test"); 
            aService.fooA("JUnit test fooA"); 
            aService.barA(); 
            bService.fooB(); 
            bService.barB("JUnit test barB",0); 
        } 
         
        /**
         * 测试After-Throwing
         */ 
        public void testThrow() 
        { 
                
            try { 
                bService.barB("JUnit call barB",1); 
            } catch (IllegalArgumentException e) { 
                 
            } 
        } 
         
        public void setAService(AService service) { 
            aService = service; 
        } 
         
        public void setBService(BServiceImpl service) { 
            bService = service; 
        } 
    }


     

    运行结果如下:

    log Begining method: com.spring.service.AServiceImpl.fooA

    AServiceImpl.fooA(msg:JUnit test fooA)

    log Ending method: com.spring.service.AServiceImpl.fooA

    process time: 0 ms

    log Begining method: com.spring.service.AServiceImpl.barA

    AServiceImpl.barA()

    log Ending method: com.spring.service.AServiceImpl.barA

    process time: 0 ms

    log Begining method: com.spring.service.BServiceImpl.fooB

    BServiceImpl.fooB()

    log Ending method: com.spring.service.BServiceImpl.fooB

    process time: 0 ms

    log Begining method: com.spring.service.BServiceImpl.barB

    BServiceImpl.barB(msg:JUnit test barB type:0)

    log Ending method: com.spring.service.BServiceImpl.barB

    process time: 0 ms

     

    log Begining method: com.spring.service.BServiceImpl.barB

    BServiceImpl.barB(msg:JUnit call barB type:1)

    log Ending method: com.spring.service.BServiceImpl.barB

    method com.spring.service.BServiceImpl.barB throw exception

     

    Spring参考手册》中定义了以下几个AOP的重要概念,结合以上代码分析如下:

    切面(Aspect) :官方的抽象定义为“一个关注点的模块化,这个关注点可能会横切多个对象”,在本例中,“切面”就是类TestAspect所关注的具体行为,例如,AServiceImpl.barA()的调用就是切面TestAspect所关注的行为之一。“切面”在ApplicationContext<aop:aspect>来配置。

     

    连接点(Joinpoint) :程序执行过程中的某一行为,例如,AServiceImpl.barA()的调用或者BServiceImpl.barB(String _msg, int _type)抛出异常等行为。

     

    通知(Advice) :“切面”对于某个“连接点”所产生的动作,例如,TestAspect中对com.spring.service包下所有类的方法进行日志记录的动作就是一个Advice。其中,一个“切面”可以包含多个“Advice”

     

    切入点(Pointcut) :匹配连接点的断言,在AOP中通知和一个切入点表达式关联。例如,TestAspect中的所有通知所关注的连接点,都由切入点表达式execution(* com.spring.service.*.*(..))来决定

     

    目标对象(Target Object) :被一个或者多个切面所通知的对象。例如,AServcieImplBServiceImpl,当然在实际运行时,Spring AOP采用代理实现,实际AOP操作的是TargetObject的代理对象。

     

    AOP代理(AOP Proxy) Spring AOP中有两种代理方式,JDK动态代理和CGLIB代理。默认情况下,TargetObject实现了接口时,则采用JDK动态代理,例如,AServiceImpl;反之,采用CGLIB代理,例如,BServiceImpl。强制使用CGLIB代理需要将 <aop:config>  proxy-target-class 属性设为true

     

          通知(Advice)类型

    前置通知(Before advice) :在某连接点(JoinPoint)之前执行的通知,但这个通知不能阻止连接点前的执行。ApplicationContext中在<aop:aspect>里面使用<aop:before>元素进行声明。例如,TestAspect中的doBefore方法

    后通知(After advice) :当某连接点退出的时候执行的通知(不论是正常返回还是异常退出)。ApplicationContext中在<aop:aspect>里面使用<aop:after>元素进行声明。例如,TestAspect中的doAfter方法,所以AOPTest中调用BServiceImpl.barB抛出异常时,doAfter方法仍然执行

    返回后通知(After return advice) :在某连接点正常完成后执行的通知,不包括抛出异常的情况。ApplicationContext中在<aop:aspect>里面使用<after-returning>元素进行声明。

    环绕通知(Around advice) :包围一个连接点的通知,类似WebServlet规范中的FilterdoFilter方法。可以在方法的调用前后完成自定义的行为,也可以选择不执行。ApplicationContext中在<aop:aspect>里面使用<aop:around>元素进行声明。例如,TestAspect中的doAround方法。

    抛出异常后通知(After throwing advice) 在方法抛出异常退出时执行的通知。 ApplicationContext中在<aop:aspect>里面使用<aop:after-throwing>元素进行声明。例如,TestAspect中的doThrowing方法。

     

           切入点表达式

    通常情况下,表达式中使用”execution“就可以满足大部分的要求。表达式格式如下: 

    execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)  

    modifiers-pattern:方法的操作权限

    ret-type-pattern:返回值

    declaring-type-pattern:方法所在的包

    name-pattern:方法名

    parm-pattern:参数名

    throws-pattern:异常

    其中,除ret-type-pattern和name-pattern之外,其他都是可选的。上例中,execution(* com.spring.service.*.*(..))表示com.spring.service包下,返回值为任意类型;方法名任意;参数不作限制的所有方法。

    访问当前的连接点

    任何通知(Advice)方法可以将第一个参数定义为 org.aspectj.lang.JoinPoint 类型。JoinPoint 接口提供了一系列有用的方法,比如 getArgs() (返回方法参数)、getThis() (返回代理对象)、getTarget() (返回目标)、getSignature() (返回正在被通知的方法相关信息)和 toString() (打印出正在被通知的方法的有用信息。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值