aop是spring的兩大功能模塊之一,功能很是強大,爲解耦提供了很是優秀的解決方案。java
如今就以springboot中aop的使用來了解一下aop。web
一:使用aop來完成全局請求日誌處理
建立一個springboot的web項目,勾選aop,pom以下:spring
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <groupId>com.example</groupId>
- <artifactId>testaop</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>jar</packaging>
-
- <name>testaop</name>
- <description>Demo project for Spring Boot</description>
-
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>1.5.3.RELEASE</version>
- <relativePath/>
- </parent>
-
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
- <java.version>1.8</java.version>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-aop</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
-
-
- </project>
建立個controller
- package com.example.controller;
-
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RestController;
-
- @RestController
- public class FirstController {
-
- @RequestMapping("/first")
- public Object first() {
- return "first controller";
- }
-
- @RequestMapping("/doError")
- public Object error() {
- return 1 / 0;
- }
- }
建立一個aspect切面類
- package com.example.aop;
-
- import org.aspectj.lang.JoinPoint;
- import org.aspectj.lang.ProceedingJoinPoint;
- import org.aspectj.lang.annotation.*;
- import org.springframework.stereotype.Component;
- import org.springframework.web.context.request.RequestContextHolder;
- import org.springframework.web.context.request.ServletRequestAttributes;
-
- import javax.servlet.http.HttpServletRequest;
- import java.util.Arrays;
-
- @Aspect
- @Component
- public class LogAspect {
- @Pointcut("execution(public * com.example.controller.*.*(..))")
- public void webLog(){}
-
- @Before("webLog()")
- public void deBefore(JoinPoint joinPoint) throws Throwable {
-
- ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
- HttpServletRequest request = attributes.getRequest();
-
- System.out.println("URL : " + request.getRequestURL().toString());
- System.out.println("HTTP_METHOD : " + request.getMethod());
- System.out.println("IP : " + request.getRemoteAddr());
- System.out.println("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
- System.out.println("ARGS : " + Arrays.toString(joinPoint.getArgs()));
-
- }
-
- @AfterReturning(returning = "ret", pointcut = "webLog()")
- public void doAfterReturning(Object ret) throws Throwable {
-
- System.out.println("方法的返回值 : " + ret);
- }
-
-
- @AfterThrowing("webLog()")
- public void throwss(JoinPoint jp){
- System.out.println("方法異常時執行.....");
- }
-
-
- @After("webLog()")
- public void after(JoinPoint jp){
- System.out.println("方法最後執行.....");
- }
-
-
- @Around("webLog()")
- public Object arround(ProceedingJoinPoint pjp) {
- System.out.println("方法環繞start.....");
- try {
- Object o = pjp.proceed();
- System.out.println("方法環繞proceed,結果是 :" + o);
- return o;
- } catch (Throwable e) {
- e.printStackTrace();
- return null;
- }
- }
- }
啓動項目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",供讀取異常信息,如本例中能夠改成:
- @AfterThrowing(throwing = "ex", pointcut = "webLog()")
- public void throwss(JoinPoint jp, Exception ex){
- System.out.println("方法異常時執行.....");
- }
通常經常使用的有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的。
四:自定義註解
通常多用於某些特定的功能,比較零散的切面,譬如特定的某些方法須要處理,就能夠單獨在方法上加註解切面。
咱們來自定義一個註解:
- package com.example.aop;
-
- import java.lang.annotation.ElementType;
- import java.lang.annotation.Retention;
- import java.lang.annotation.RetentionPolicy;
- import java.lang.annotation.Target;
-
- @Target({ElementType.METHOD, ElementType.TYPE})
- @Retention(RetentionPolicy.RUNTIME)
- public @interface UserAccess {
- String desc() default "無信息";
- }
註解裏提供了一個desc的方法,供被切面的地方傳參,若是不須要傳參能夠不寫。
在Controller里加個方法
- @RequestMapping("/second")
- @UserAccess(desc = "second")
- public Object second() {
- return "second controller";
- }
切面類:
- package com.example.aop;
-
- import org.aspectj.lang.JoinPoint;
- import org.aspectj.lang.ProceedingJoinPoint;
- import org.aspectj.lang.annotation.*;
- import org.springframework.stereotype.Component;
-
- @Component
- @Aspect
- public class UserAccessAspect {
-
- @Pointcut(value = "@annotation(com.example.aop.UserAccess)")
- public void access() {
-
- }
-
- @Before("access()")
- public void deBefore(JoinPoint joinPoint) throws Throwable {
- System.out.println("second before");
- }
-
- @Around("@annotation(userAccess)")
- public Object around(ProceedingJoinPoint pjp, UserAccess userAccess) {
-
- System.out.println("second around:" + userAccess.desc());
- try {
- return pjp.proceed();
- } catch (Throwable throwable) {
- throwable.printStackTrace();
- return null;
- }
- }
- }
主要看一下@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切面類都工做了,順序呢就是下面的
![](http://static.javashuo.com/static/loading.gif)
spring aop就是一個同心圓,要執行的方法爲圓心,最外層的order最小。從最外層按照AOP一、AOP2的順序依次執行doAround方法,doBefore方法。而後執行method方法,最後按照AOP二、AOP1的順序依次執行doAfter、doAfterReturn方法。也就是說對多個AOP來講,先before的,必定後after。對於上面的例子就是,先外層的就是對全部controller的切面,內層就是自定義註解的。那不一樣的切面,順序怎麼決定呢,尤爲是同格式的切面處理,譬如兩個execution的狀況,那spring就是隨機決定哪一個在外哪一個在內了。因此大部分狀況下,咱們須要指定順序,最簡單的方式就是在Aspect切面類上加上@Order(1)註解便可,order越小最早執行,也就是位於最外層。像一些全局處理的就能夠把order設小一點,具體到某個細節的就設大一點。