【SSH进阶之路】Spring的AOP逐层深入——采用注解完成AOP(七)

 上篇博文【SSH进阶之路】Spring的AOP逐层深入——AOP的基本原理(六),我们介绍了AOP的基本原理,以及5种通知的类型,

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

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

        

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

 

[java] view plain copy
 
 print?
  1. package com.tgb.spring;  
  2.   
  3. public interface UserManager {  
  4.   
  5.     public void addUser(String userName,String password);  
  6.       
  7.     public void delUser(int userId);  
  8.       
  9.     public String findUserById(int userId);  
  10.       
  11.     public void modifyUser(int userId,String userName,String password);  
  12. }  
[java] view plain copy
 
 print?
  1. package com.tgb.spring;  
  2.   
  3. public class UserManagerImpl implements UserManager {  
  4.   
  5.     @Override  
  6.     public void addUser(String userName, String password) {  
  7.         System.out.println("----UserManagerImpl.add()----");  
  8.     }  
  9.   
  10.     @Override  
  11.     public void delUser(int userId) {  
  12.         System.out.println("----UserManagerImpl.delUser()----");  
  13.     }  
  14.   
  15.     @Override  
  16.     public String findUserById(int userId) {  
  17.           
  18.         System.out.println("----UserManagerImpl.findUserById()----");  
  19.           
  20.         if(userId <= 0){  
  21.             throw new IllegalArgumentException("该用户不存在");  
  22.         }  
  23.         return "jiuqiyuliang";  
  24.     }  
  25.   
  26.     @Override  
  27.     public void modifyUser(int userId, String userName, String password) {  
  28.         System.out.println("----UserManagerImpl.modifyUser()----");  
  29.     }  
  30.   
  31. }  

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

[java] view plain copy
 
 print?
  1. package com.tgb.spring;  
  2.   
  3. import org.aspectj.lang.JoinPoint;  
  4. import org.aspectj.lang.ProceedingJoinPoint;  
  5. import org.aspectj.lang.annotation.After;  
  6. import org.aspectj.lang.annotation.AfterReturning;  
  7. import org.aspectj.lang.annotation.AfterThrowing;  
  8. import org.aspectj.lang.annotation.Around;  
  9. import org.aspectj.lang.annotation.Aspect;  
  10. import org.aspectj.lang.annotation.Before;  
  11. import org.aspectj.lang.annotation.Pointcut;  
  12.   
  13. @Aspect  
  14. public class AspectJAdvice {  
  15.   
  16.     /** 
  17.      * Pointcut 
  18.      * 定义Pointcut,Pointcut的名称为aspectjMethod(),此方法没有返回值和参数 
  19.      * 该方法就是一个标识,不进行调用 
  20.      */  
  21.     @Pointcut("execution(* find*(..))")  
  22.     private void aspectjMethod(){};  
  23.       
  24.     /**  
  25.      * Before 
  26.      * 在核心业务执行前执行,不能阻止核心业务的调用。 
  27.      * @param joinPoint  
  28.      */    
  29.     @Before("aspectjMethod()")    
  30.     public void doBefore(JoinPoint joinPoint) {    
  31.         System.out.println("-----doBefore.invoke-----");  
  32.         System.out.println(" 此处意在执行核心业务逻辑前,做一些安全性的判断等等");  
  33.         System.out.println(" 可通过joinPoint来获取所需要的内容");  
  34.         System.out.println("-----End of doBefore()------");  
  35.     }  
  36.       
  37.       
  38.   
  39.     /**  
  40.      * Around  
  41.      * 手动控制调用核心业务逻辑,以及调用前和调用后的处理, 
  42.      *  
  43.      * 注意:当核心业务抛异常后,立即退出,转向AfterAdvice 
  44.      * 执行完AfterAdvice,再转到ThrowingAdvice 
  45.      * @param pjp 
  46.      * @return 
  47.      * @throws Throwable 
  48.      */   
  49.     @Around(value = "aspectjMethod()")    
  50.     public Object doAround(ProceedingJoinPoint pjp) throws Throwable {    
  51.         System.out.println("-----doAround.invoke-----");  
  52.         System.out.println(" 此处可以做类似于Before的事情");  
  53.           
  54.         //调用核心逻辑  
  55.         Object retVal = pjp.proceed();  
  56.         System.out.println(" 此处可以做类似于After的事情");  
  57.         System.out.println("-----End of doAround()------");  
  58.         return retVal;  
  59.     }    
  60.       
  61.       
  62.     /**  
  63.      * After  
  64.      * 核心业务逻辑退出后(包括正常执行结束和异常退出),执行此Advice 
  65.      * @param joinPoint 
  66.      */  
  67.     @After(value = "aspectjMethod()")    
  68.     public void doAfter(JoinPoint joinPoint) {    
  69.         System.out.println("-----doAfter.invoke-----");  
  70.         System.out.println(" 此处意在执行核心业务逻辑之后,做一些日志记录操作等等");  
  71.         System.out.println(" 可通过joinPoint来获取所需要的内容");  
  72.         System.out.println("-----End of doAfter()------");  
  73.     }    
  74.       
  75.     /**  
  76.      * AfterReturning  
  77.      * 核心业务逻辑调用正常退出后,不管是否有返回值,正常退出后,均执行此Advice 
  78.      * @param joinPoint 
  79.      */   
  80.     @AfterReturning(value = "aspectjMethod()", returning = "retVal")    
  81.     public void doReturn(JoinPoint joinPoint, String retVal) {    
  82.         System.out.println("-----doReturn().invoke-----");  
  83.         System.out.println("Return Value: " + retVal);   
  84.         System.out.println(" 此处可以对返回值做进一步处理");  
  85.         System.out.println(" 可通过joinPoint来获取所需要的内容");  
  86.         System.out.println("-----End of doReturn()------");  
  87.     }  
  88.       
  89.     /** 
  90.      * 核心业务逻辑调用异常退出后,执行此Advice,处理错误信息 
  91.      *  
  92.      * 注意:执行顺序在Around Advice之后 
  93.      * @param joinPoint 
  94.      * @param ex 
  95.      */  
  96.     @AfterThrowing(value = "aspectjMethod()", throwing = "ex")    
  97.     public void doThrowing(JoinPoint joinPoint, Exception ex) {    
  98.         System.out.println("-----doThrowing().invoke-----");  
  99.         System.out.println(" 错误信息:"+ex.getMessage());  
  100.         System.out.println(" 此处意在执行核心业务逻辑出错时,捕获异常,并可做一些日志记录操作等等");  
  101.         System.out.println(" 可通过joinPoint来获取所需要的内容");  
  102.         System.out.println("-----End of doThrowing()------");    
  103.     }    
  104. }  

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

[html] view plain copy
 
 print?
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2.   
  3. <beans xmlns="http://www.springframework.org/schema/beans"  
  4.          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.          xmlns:aop="http://www.springframework.org/schema/aop"  
  6.          xmlns:tx="http://www.springframework.org/schema/tx"  
  7.          xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd  
  8.            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd  
  9.            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">  
  10.   
  11.     <!-- 启用Spring对基于@AspectJ aspects的配置支持 -->  
  12.     <aop:aspectj-autoproxy></aop:aspectj-autoproxy>  
  13.       
  14.     <bean id="userManager" class="com.tgb.spring.UserManagerImpl"></bean>  
  15.       
  16.     <bean id="aspectJAdvice" class="com.tgb.spring.AspectJAdvice"></bean>  
  17.       
  18. </beans>  

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

[java] view plain copy
 
 print?
  1. package com.tgb.spring;  
  2.   
  3. import org.springframework.beans.factory.BeanFactory;  
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  5.   
  6. public class Client {  
  7.   
  8.     public static void main(String[] args) {  
  9.         BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");  
  10.           
  11.         UserManager userManager = (UserManager) factory.getBean("userManager");  
  12.         //可以查找张三  
  13.         userManager.findUserById(1);  
  14.           
  15.         System.out.println("=====我==是==分==割==线=====");  
  16.           
  17.         try {  
  18.             // 查不到数据,会抛异常,异常会被AfterThrowingAdvice捕获  
  19.             userManager.findUserById(0);  
  20.         } catch (IllegalArgumentException e) {  
  21.         }  
  22.     }  
  23. }  


运行结果如图:

    

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

 

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

 

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

posted on 2017-07-17 17:03  alex5211314  阅读(197)  评论(0编辑  收藏  举报

导航