Spring的AOP逐层深入——采用注解完成AOP(七)

上篇博文AOP基本原理6我们介绍了AOP的基本原理,以及5种通知的类型,

AOP的两种配置方式:XML配置和Aspectj注解方式。

        这篇我们使用注解方式来实现一个AOP,我们先看一下项目的目录。

        

         我们采用的是JDK代理,所以首先将接口和实现类代码附上:

[java] view plain copy

  1. package com.tgb.spring;  

  2. public interface UserManager {  

  3.     public void addUser(String userName,String password);  

  4.     public void delUser(int userId);  

  5.     public String findUserById(int userId);  

  6.     public void modifyUser(int userId,String userName,String password);  

  7. }

  

[java] view plain copy

  1. package com.tgb.spring;  

  2. public class UserManagerImpl implements UserManager {  

  3.     @Override  

  4.     public void addUser(String userName, String password) {  

  5.         System.out.println("----UserManagerImpl.add()----");  

  6.     }  

  7.     @Override  

  8.     public void delUser(int userId) {  

  9.         System.out.println("----UserManagerImpl.delUser()----");  

  10.     }  

  11.     @Override  

  12.     public String findUserById(int userId) {  

  13.         System.out.println("----UserManagerImpl.findUserById()----");  

  14.         if(userId <= 0){  

  15.             throw new IllegalArgumentException("该用户不存在");  

  16.         }  

  17.         return "jiuqiyuliang";  

  18.     }  

  19.     @Override  

  20.     public void modifyUser(int userId, String userName, String password) {  

  21.         System.out.println("----UserManagerImpl.modifyUser()----");  

  22.     }  

  23. }

  

       上面代码跟我们平时写的一样,关键看我们的切面类,同理,切面类可以换成安全性检测以及日志管理等等:

[java] view plain copy

  1. package com.tgb.spring;  

  2. import org.aspectj.lang.JoinPoint;  

  3. import org.aspectj.lang.ProceedingJoinPoint;  

  4. import org.aspectj.lang.annotation.After;  

  5. import org.aspectj.lang.annotation.AfterReturning;  

  6. import org.aspectj.lang.annotation.AfterThrowing;  

  7. import org.aspectj.lang.annotation.Around;  

  8. import org.aspectj.lang.annotation.Aspect;  

  9. import org.aspectj.lang.annotation.Before;  

  10. import org.aspectj.lang.annotation.Pointcut;  

  11. @Aspect  

  12. public class AspectJAdvice {  

  13.     /** 

  14.      * Pointcut 

  15.      * 定义Pointcut,Pointcut的名称为aspectjMethod(),此方法没有返回值和参数 

  16.      * 该方法就是一个标识,不进行调用 

  17.      */  

  18.     @Pointcut("execution(* find*(..))")  

  19.     private void aspectjMethod(){};  

  20.     /**  

  21.      * Before 

  22.      * 在核心业务执行前执行,不能阻止核心业务的调用。 

  23.      * @param joinPoint  

  24.      */    

  25.     @Before("aspectjMethod()")    

  26.     public void doBefore(JoinPoint joinPoint) {    

  27.         System.out.println("-----doBefore.invoke-----");  

  28.         System.out.println(" 此处意在执行核心业务逻辑前,做一些安全性的判断等等");  

  29.         System.out.println(" 可通过joinPoint来获取所需要的内容");  

  30.         System.out.println("-----End of doBefore()------");  

  31.     }  

  32.     /**  

  33.      * Around  

  34.      * 手动控制调用核心业务逻辑,以及调用前和调用后的处理, 

  35.      *  

  36.      * 注意:当核心业务抛异常后,立即退出,转向AfterAdvice 

  37.      * 执行完AfterAdvice,再转到ThrowingAdvice 

  38.      * @param pjp 

  39.      * @return 

  40.      * @throws Throwable 

  41.      */   

  42.     @Around(value = "aspectjMethod()")    

  43.     public Object doAround(ProceedingJoinPoint pjp) throws Throwable {    

  44.         System.out.println("-----doAround.invoke-----");  

  45.         System.out.println(" 此处可以做类似于Before的事情");  

  46.         //调用核心逻辑  

  47.         Object retVal = pjp.proceed();  

  48.         System.out.println(" 此处可以做类似于After的事情");  

  49.         System.out.println("-----End of doAround()------");  

  50.         return retVal;  

  51.     }    

  52.     /**  

  53.      * After  

  54.      * 核心业务逻辑退出后(包括正常执行结束和异常退出),执行此Advice 

  55.      * @param joinPoint 

  56.      */  

  57.     @After(value = "aspectjMethod()")    

  58.     public void doAfter(JoinPoint joinPoint) {    

  59.         System.out.println("-----doAfter.invoke-----");  

  60.         System.out.println(" 此处意在执行核心业务逻辑之后,做一些日志记录操作等等");  

  61.         System.out.println(" 可通过joinPoint来获取所需要的内容");  

  62.         System.out.println("-----End of doAfter()------");  

  63.     }    

  64.     /**  

  65.      * AfterReturning  

  66.      * 核心业务逻辑调用正常退出后,不管是否有返回值,正常退出后,均执行此Advice 

  67.      * @param joinPoint 

  68.      */   

  69.     @AfterReturning(value = "aspectjMethod()", returning = "retVal")    

  70.     public void doReturn(JoinPoint joinPoint, String retVal) {    

  71.         System.out.println("-----doReturn().invoke-----");  

  72.         System.out.println("Return Value: " + retVal);   

  73.         System.out.println(" 此处可以对返回值做进一步处理");  

  74.         System.out.println(" 可通过joinPoint来获取所需要的内容");  

  75.         System.out.println("-----End of doReturn()------");  

  76.     }  

  77.     /** 

  78.      * 核心业务逻辑调用异常退出后,执行此Advice,处理错误信息 

  79.      *  

  80.      * 注意:执行顺序在Around Advice之后 

  81.      * @param joinPoint 

  82.      * @param ex 

  83.      */  

  84.     @AfterThrowing(value = "aspectjMethod()", throwing = "ex")    

  85.     public void doThrowing(JoinPoint joinPoint, Exception ex) {    

  86.         System.out.println("-----doThrowing().invoke-----");  

  87.         System.out.println(" 错误信息:"+ex.getMessage());  

  88.         System.out.println(" 此处意在执行核心业务逻辑出错时,捕获异常,并可做一些日志记录操作等等");  

  89.         System.out.println(" 可通过joinPoint来获取所需要的内容");  

  90.         System.out.println("-----End of doThrowing()------");    

  91.     }    

  92. }

  

       我们配置完切面类之后,还需要将Spring的IOC和AOP结合:

[html] view plain copy

  1.   

  2. <beans xmlns="http://www.springframework.org/schema/beans"  

  3.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  

  4.          xmlns:aop="http://www.springframework.org/schema/aop"  

  5.          xmlns:tx="http://www.springframework.org/schema/tx"  

  6.          xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd  

  7.            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd  

  8.            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">  

  9.       

  10.     aop:aspectj-autoproxy  

  11.       

  12.       

  

         所有都完成之后,最重要的一步就是编写客户端,进行测试,看是否和我们预想的结果一致。

[java] view plain copy

  1. package com.tgb.spring;  

  2. import org.springframework.beans.factory.BeanFactory;  

  3. import org.springframework.context.support.ClassPathXmlApplicationContext;  

  4. public class Client {  

  5.     public static void main(String[] args) {  

  6.         BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");  

  7.         UserManager userManager = (UserManager) factory.getBean("userManager");  

  8.         //可以查找张三  

  9.         userManager.findUserById(1);  

  10.         System.out.println("=====我==是==分==割==线=====");  

  11.         try {  

  12.             // 查不到数据,会抛异常,异常会被AfterThrowingAdvice捕获  

  13.             userManager.findUserById(0);  

  14.         } catch (IllegalArgumentException e) {  

  15.         }  

  16.     }  

  17. }

  

运行结果如图:

    

              正常运行,无异常抛出(一)                                                                                         不正常运行,有异常抛出(二)

         上面两张图的目的为了给大家描述Advice五种类型的运行顺序,让大家对他们有一个更加清晰的认识。

         使用注解方式可以很好的帮助我们理解AOP的原理,如果对AOP的原理不是特别清晰,可以看一下上篇博文的图。下面我们采用xml方式再实现一遍AOP。

评论

暂无评论