Spring boot中使用aop詳解

 
 
 
 

aop是spring的兩大功能模塊之一,功能很是強大,爲解耦提供了很是優秀的解決方案。java

如今就以springboot中aop的使用來了解一下aop。web

 

一:使用aop來完成全局請求日誌處理

建立一個springboot的web項目,勾選aop,pom以下:spring

 

[html]  view plain  copy
 
 print?
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">  
  4.     <modelVersion>4.0.0</modelVersion>  
  5.   
  6.     <groupId>com.example</groupId>  
  7.     <artifactId>testaop</artifactId>  
  8.     <version>0.0.1-SNAPSHOT</version>  
  9.     <packaging>jar</packaging>  
  10.   
  11.     <name>testaop</name>  
  12.     <description>Demo project for Spring Boot</description>  
  13.   
  14.     <parent>  
  15.         <groupId>org.springframework.boot</groupId>  
  16.         <artifactId>spring-boot-starter-parent</artifactId>  
  17.         <version>1.5.3.RELEASE</version>  
  18.         <relativePath/> <!-- lookup parent from repository -->  
  19.     </parent>  
  20.   
  21.     <properties>  
  22.         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
  23.         <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>  
  24.         <java.version>1.8</java.version>  
  25.     </properties>  
  26.   
  27.     <dependencies>  
  28.         <dependency>  
  29.             <groupId>org.springframework.boot</groupId>  
  30.             <artifactId>spring-boot-starter-aop</artifactId>  
  31.         </dependency>  
  32.         <dependency>  
  33.             <groupId>org.springframework.boot</groupId>  
  34.             <artifactId>spring-boot-starter-web</artifactId>  
  35.         </dependency>  
  36.   
  37.         <dependency>  
  38.             <groupId>org.springframework.boot</groupId>  
  39.             <artifactId>spring-boot-starter-test</artifactId>  
  40.             <scope>test</scope>  
  41.         </dependency>  
  42.     </dependencies>  
  43.   
  44.     <build>  
  45.         <plugins>  
  46.             <plugin>  
  47.                 <groupId>org.springframework.boot</groupId>  
  48.                 <artifactId>spring-boot-maven-plugin</artifactId>  
  49.             </plugin>  
  50.         </plugins>  
  51.     </build>  
  52.   
  53.   
  54. </project>  
建立個controller

 

 

[java]  view plain  copy
 
 print?
  1. package com.example.controller;  
  2.   
  3. import org.springframework.web.bind.annotation.RequestMapping;  
  4. import org.springframework.web.bind.annotation.RestController;  
  5.   
  6. /** 
  7.  * Created by wuwf on 17/4/27. 
  8.  * 
  9.  */  
  10. @RestController  
  11. public class FirstController {  
  12.   
  13.     @RequestMapping("/first")  
  14.     public Object first() {  
  15.         return "first controller";  
  16.     }  
  17.   
  18.     @RequestMapping("/doError")  
  19.     public Object error() {  
  20.         return 1 / 0;  
  21.     }  
  22. }  
建立一個aspect切面類

 

 

[java]  view plain  copy
 
 print?
  1. package com.example.aop;  
  2.   
  3. import org.aspectj.lang.JoinPoint;  
  4. import org.aspectj.lang.ProceedingJoinPoint;  
  5. import org.aspectj.lang.annotation.*;  
  6. import org.springframework.stereotype.Component;  
  7. import org.springframework.web.context.request.RequestContextHolder;  
  8. import org.springframework.web.context.request.ServletRequestAttributes;  
  9.   
  10. import javax.servlet.http.HttpServletRequest;  
  11. import java.util.Arrays;  
  12.   
  13. /** 
  14.  * Created by wuwf on 17/4/27. 
  15.  * 日誌切面 
  16.  */  
  17. @Aspect  
  18. @Component  
  19. public class LogAspect {  
  20.     @Pointcut("execution(public * com.example.controller.*.*(..))")  
  21.     public void webLog(){}  
  22.   
  23.     @Before("webLog()")  
  24.     public void deBefore(JoinPoint joinPoint) throws Throwable {  
  25.         // 接收到請求,記錄請求內容  
  26.         ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();  
  27.         HttpServletRequest request = attributes.getRequest();  
  28.         // 記錄下請求內容  
  29.         System.out.println("URL : " + request.getRequestURL().toString());  
  30.         System.out.println("HTTP_METHOD : " + request.getMethod());  
  31.         System.out.println("IP : " + request.getRemoteAddr());  
  32.         System.out.println("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());  
  33.         System.out.println("ARGS : " + Arrays.toString(joinPoint.getArgs()));  
  34.   
  35.     }  
  36.   
  37.     @AfterReturning(returning = "ret", pointcut = "webLog()")  
  38.     public void doAfterReturning(Object ret) throws Throwable {  
  39.         // 處理完請求,返回內容  
  40.         System.out.println("方法的返回值 : " + ret);  
  41.     }  
  42.   
  43.     //後置異常通知  
  44.     @AfterThrowing("webLog()")  
  45.     public void throwss(JoinPoint jp){  
  46.         System.out.println("方法異常時執行.....");  
  47.     }  
  48.   
  49.     //後置最終通知,final加強,不論是拋出異常或者正常退出都會執行  
  50.     @After("webLog()")  
  51.     public void after(JoinPoint jp){  
  52.         System.out.println("方法最後執行.....");  
  53.     }  
  54.   
  55.     //環繞通知,環繞加強,至關於MethodInterceptor  
  56.     @Around("webLog()")  
  57.     public Object arround(ProceedingJoinPoint pjp) {  
  58.         System.out.println("方法環繞start.....");  
  59.         try {  
  60.             Object o =  pjp.proceed();  
  61.             System.out.println("方法環繞proceed,結果是 :" + o);  
  62.             return o;  
  63.         } catch (Throwable e) {  
  64.             e.printStackTrace();  
  65.             return null;  
  66.         }  
  67.     }  
  68. }  

啓動項目apache

模擬正常執行的狀況,訪問http://localhost:8080/first,看控制檯結果:springboot

 

方法環繞start.....
URL : http://localhost:8080/first
HTTP_METHOD : GET
IP : 0:0:0:0:0:0:0:1
CLASS_METHOD : com.example.controller.FirstController.first
ARGS : []
方法環繞proceed,結果是 :first controller
方法最後執行.....
方法的返回值 : first controllerapp

/****************************分割線****************************/maven

模擬出現異常時的狀況,訪問http://localhost:8080/doError,看控制檯結果:
方法環繞start.....
URL : http://localhost:8080/doError
HTTP_METHOD : GET
IP : 0:0:0:0:0:0:0:1
CLASS_METHOD : com.example.controller.FirstController.error
ARGS : []
java.lang.ArithmeticException: / by zero函數

......spring-boot

方法最後執行.....
方法的返回值 : null

/****************************分割線****************************/

經過上面的簡單的例子,能夠看到aop的執行順序。知道了順序後,就能夠在相應的位置作切面處理了。

 

二: 切面方法說明

@Aspect

做用是把當前類標識爲一個切面供容器讀取

@Before
標識一個前置加強方法,至關於BeforeAdvice的功能

@AfterReturning

後置加強,至關於AfterReturningAdvice,方法退出時執行

@AfterThrowing

異常拋出加強,至關於ThrowsAdvice

@After

final加強,不論是拋出異常或者正常退出都會執行

@Around

環繞加強,至關於MethodInterceptor

/****************************分割線****************************/

各方法參數說明:

除了@Around外,每一個方法裏均可以加或者不加參數JoinPoint,若是有用JoinPoint的地方就加,不加也能夠,JoinPoint裏包含了類名、被切面的方法名,參數等屬性,可供讀取使用。@Around參數必須爲ProceedingJoinPoint,pjp.proceed相應於執行被切面的方法。@AfterReturning方法裏,能夠加returning = 「XXX」,XXX即爲在controller裏方法的返回值,本例中的返回值是「first controller」。@AfterThrowing方法裏,能夠加throwing = "XXX",供讀取異常信息,如本例中能夠改成:

 

[java]  view plain  copy
 
 print?
  1. //後置異常通知  
  2.     @AfterThrowing(throwing = "ex", pointcut = "webLog()")  
  3.     public void throwss(JoinPoint jp, Exception ex){  
  4.         System.out.println("方法異常時執行.....");  
  5.     }  

通常經常使用的有before和afterReturn組合,或者單獨使用Around,便可獲取方法開始前和結束後的切面。

 

三:關於切面PointCut的切入點

 

execution切點函數

 

execution函數用於匹配方法執行的鏈接點,語法爲:

execution(方法修飾符(可選)  返回類型  方法名  參數  異常模式(可選)) 

參數部分容許使用通配符:

*  匹配任意字符,但只能匹配一個元素

.. 匹配任意字符,能夠匹配任意多個元素,表示類時,必須和*聯合使用

+  必須跟在類名後面,如Horseman+,表示類自己和繼承或擴展指定類的全部類

參考:http://blog.csdn.net/autfish/article/details/51184405

 

除了execution(),Spring中還支持其餘多個函數,這裏列出名稱和簡單介紹,以方便根據須要進行更詳細的查詢

 @annotation()

表示標註了指定註解的目標類方法

例如 @annotation(org.springframework.transaction.annotation.Transactional) 表示標註了@Transactional的方法

args()

經過目標類方法的參數類型指定切點

例如 args(String) 表示有且僅有一個String型參數的方法

@args()

經過目標類參數的對象類型是否標註了指定註解指定切點

如 @args(org.springframework.stereotype.Service) 表示有且僅有一個標註了@Service的類參數的方法

within()

經過類名指定切點

如 with(examples.chap03.Horseman) 表示Horseman的全部方法

target()

經過類名指定,同時包含全部子類

如 target(examples.chap03.Horseman)  且Elephantman extends Horseman,則兩個類的全部方法都匹配

@within()

匹配標註了指定註解的類及其全部子類

如 @within(org.springframework.stereotype.Service) 給Horseman加上@Service標註,則Horseman和Elephantman 的全部方法都匹配

@target()

全部標註了指定註解的類

如 @target(org.springframework.stereotype.Service) 表示全部標註了@Service的類的全部方法

 this()

大部分時候和target()相同,區別是this是在運行時生成代理類後,才判斷代理類與指定的對象類型是否匹配

 

/****************************分割線****************************/

 

邏輯運算符

表達式可由多個切點函數經過邏輯運算組成

 &&

與操做,求交集,也能夠寫成and

例如 execution(* chop(..)) && target(Horseman)  表示Horseman及其子類的chop方法

 ||

或操做,求並集,也能夠寫成or

例如 execution(* chop(..)) || args(String)  表示名稱爲chop的方法或者有一個String型參數的方法

!

非操做,求反集,也能夠寫成not

例如 execution(* chop(..)) and !args(String)  表示名稱爲chop的方法可是不能是隻有一個String型參數的方法

 

execution經常使用於匹配特定的方法,如update時怎麼處理,或者匹配某些類,如全部的controller類,是一種範圍較大的切面方式,多用於日誌或者事務處理等。

其餘的幾個用法各有千秋,視狀況而選擇。

以上標紅的比較經常使用。下面來看annotation的。

四:自定義註解

通常多用於某些特定的功能,比較零散的切面,譬如特定的某些方法須要處理,就能夠單獨在方法上加註解切面。

咱們來自定義一個註解:

 

[java]  view plain  copy
 
 print?
  1. package com.example.aop;  
  2.   
  3. import java.lang.annotation.ElementType;  
  4. import java.lang.annotation.Retention;  
  5. import java.lang.annotation.RetentionPolicy;  
  6. import java.lang.annotation.Target;  
  7.   
  8. /** 
  9.  * Created by wuwf on 17/4/27. 
  10.  */  
  11. @Target({ElementType.METHOD, ElementType.TYPE})  
  12. @Retention(RetentionPolicy.RUNTIME)  
  13. public @interface UserAccess {  
  14.     String desc() default "無信息";  
  15. }  
註解裏提供了一個desc的方法,供被切面的地方傳參,若是不須要傳參能夠不寫。

 

在Controller里加個方法

 

[java]  view plain  copy
 
 print?
  1. @RequestMapping("/second")  
  2.     @UserAccess(desc = "second")  
  3.     public Object second() {  
  4.         return "second controller";  
  5.     }  

切面類:

 

[java]  view plain  copy
 
 print?
  1. package com.example.aop;  
  2.   
  3. import org.aspectj.lang.JoinPoint;  
  4. import org.aspectj.lang.ProceedingJoinPoint;  
  5. import org.aspectj.lang.annotation.*;  
  6. import org.springframework.stereotype.Component;  
  7.   
  8. /** 
  9.  * Created by wuwf on 17/4/27. 
  10.  */  
  11. @Component  
  12. @Aspect  
  13. public class UserAccessAspect {  
  14.   
  15.     @Pointcut(value = "@annotation(com.example.aop.UserAccess)")  
  16.     public void access() {  
  17.   
  18.     }  
  19.   
  20.     @Before("access()")  
  21.     public void deBefore(JoinPoint joinPoint) throws Throwable {  
  22.         System.out.println("second before");  
  23.     }  
  24.   
  25.     @Around("@annotation(userAccess)")  
  26.     public Object around(ProceedingJoinPoint pjp, UserAccess userAccess) {  
  27.         //獲取註解裏的值  
  28.         System.out.println("second around:" + userAccess.desc());  
  29.         try {  
  30.             return pjp.proceed();  
  31.         } catch (Throwable throwable) {  
  32.             throwable.printStackTrace();  
  33.             return null;  
  34.         }  
  35.     }  
  36. }  

主要看一下@Around註解這裏,若是須要獲取在controller註解中賦給UserAccess的desc裏的值,就須要這種寫法,這樣UserAccess參數就有值了。

/****************************分割線****************************/

啓動項目,訪問http://localhost:8080/second,看控制檯:

 

方法環繞start.....
URL : http://localhost:8080/second
HTTP_METHOD : GET
IP : 0:0:0:0:0:0:0:1
CLASS_METHOD : com.example.controller.FirstController.second
ARGS : []
second around:second
second before
方法環繞proceed,結果是 :second controller
方法最後執行.....
方法的返回值 : second controller

/****************************分割線****************************/

通知結果能夠看到,兩個aop切面類都工做了,順序呢就是下面的

 

spring aop就是一個同心圓,要執行的方法爲圓心,最外層的order最小。從最外層按照AOP一、AOP2的順序依次執行doAround方法,doBefore方法。而後執行method方法,最後按照AOP二、AOP1的順序依次執行doAfter、doAfterReturn方法。也就是說對多個AOP來講,先before的,必定後after。對於上面的例子就是,先外層的就是對全部controller的切面,內層就是自定義註解的。那不一樣的切面,順序怎麼決定呢,尤爲是同格式的切面處理,譬如兩個execution的狀況,那spring就是隨機決定哪一個在外哪一個在內了。因此大部分狀況下,咱們須要指定順序,最簡單的方式就是在Aspect切面類上加上@Order(1)註解便可,order越小最早執行,也就是位於最外層。像一些全局處理的就能夠把order設小一點,具體到某個細節的就設大一點。

相關文章
相關標籤/搜索