一、添加aop starter依賴
<?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.chhliu.springboot.aop</groupId>
<artifactId>springboot-aop</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</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-web</artifactId>
</dependency>
<dependency><!-- spring boot aop starter依賴 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.27</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
二、配置檔案中開啟支援
spring.aop.auto=true
三、編寫切面
package com.chhliu.springboot.aop.aop;
import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.alibaba.druid.support.json.JSONUtils;
@Component // 注冊到Spring容器,必須加入這個注解
@Aspect // 該注解标示該類為切面類,切面是由通知和切點組成的。
public class ApiAspect {
private static final Logger logger = LoggerFactory.getLogger(ApiAspect.class);
ThreadLocal<Long> startTime = new ThreadLocal<Long>();
@Pointcut("execution(* com.chhliu.springboot.aop.controller.HelloController.*(..))")// 定義切點表達式
@Order(2)
public void controllerPoint() {
}
@Pointcut("@annotation(com.chhliu.springboot.aop.annotation.RedisCache)")// 定義注解類型的切點,隻要方法上有該注解,都會比對
@Order(1)
public void annotationPoint(){
}
// 定義前置通知
@Before("annotationPoint()")
public void before(JoinPoint joinPoint) {
System.out.println("方法執行前執行.....before");
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
logger.info("<====================================================================");
logger.info("請求來源: => " + request.getRemoteAddr());
logger.info("請求URL: " + request.getRequestURL().toString());
logger.info("請求方式: " + request.getMethod());
logger.info("響應方法: " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
logger.info("請求參數 : " + Arrays.toString(joinPoint.getArgs()));
logger.info("---------------------------------------------------------------------");
startTime.set(System.currentTimeMillis());
}
@Around("controllerPoint() && args(arg)")// 需要比對切點表達式,同時需要比對參數
public String around(ProceedingJoinPoint pjp, String arg) {
System.out.println("name:"+arg);
System.out.println("方法環繞start....around.");
String result = null;
try {
result = (String) pjp.proceed()+" aop String";
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("方法環繞end.....around");
return result;
}
@After("within(com.chhliu.springboot.aop.controller.*Controller)")
public void after() {
System.out.println("方法之後執行....after.");
}
@AfterReturning(pointcut="controllerPoint()", returning="rst")
public void afterReturning(JoinPoint joinPoint, Object rst) {
System.out.println("方法執行完執行.....afterReturning");
logger.info("耗時(毫秒) : " + (System.currentTimeMillis() - startTime.get()));
logger.info("傳回資料: {}", JSONUtils.toJSONString(rst));
logger.info("====================================================================>");
}
@AfterThrowing("within(com.chhliu.springboot.aop.controller.*Controller)")
public void afterThrowing() {
System.out.println("異常出現之後.....afterThrowing");
}
}
四、定義注解
package com.chhliu.springboot.aop.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 描述:加入查詢結果的緩存
* @author chhliu
* 建立時間:2017年2月14日 下午10:30:00
* @version 1.2.0
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface RedisCache {
Class<?> type();//被代理類的全類名,在之後會做為redis hash 的key
}
五、編寫Controller
package com.chhliu.springboot.aop.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.chhliu.springboot.aop.annotation.RedisCache;
@RestController
public class HelloController {
@RequestMapping(value = "/hello")
public String hello(@RequestParam(value = "name", required = true) String name) {
String result = "hello " + name;
System.out.println(result);
return result;
}
@RequestMapping(value = "/world")
public String world(@RequestParam(value = "arg", required = true) String arg){
String result = "world " + arg;
System.out.println(result);
return result;
}
@RequestMapping(value="/annotation")
@RedisCache(type=String.class)
public String annotation(){
return "annotation";
}
}
六、測試
1、啟動服務
2、在浏覽器中輸入:http://localhost:8080/annotation
3、測試結果如下:
方法執行前執行.....before
2017-02-14 15:23:42.273 INFO 2208 --- [nio-8080-exec-1] com.chhliu.springboot.aop.aop.ApiAspect : <====================================================================
2017-02-14 15:23:42.274 INFO 2208 --- [nio-8080-exec-1] com.chhliu.springboot.aop.aop.ApiAspect : 請求來源: => 127.0.0.1
2017-02-14 15:23:42.274 INFO 2208 --- [nio-8080-exec-1] com.chhliu.springboot.aop.aop.ApiAspect : 請求URL: http://localhost:8080/annotation
2017-02-14 15:23:42.274 INFO 2208 --- [nio-8080-exec-1] com.chhliu.springboot.aop.aop.ApiAspect : 請求方式: GET
2017-02-14 15:23:42.276 INFO 2208 --- [nio-8080-exec-1] com.chhliu.springboot.aop.aop.ApiAspect : 響應方法: com.chhliu.springboot.aop.controller.HelloController.annotation
2017-02-14 15:23:42.276 INFO 2208 --- [nio-8080-exec-1] com.chhliu.springboot.aop.aop.ApiAspect : 請求參數 : []
2017-02-14 15:23:42.276 INFO 2208 --- [nio-8080-exec-1] com.chhliu.springboot.aop.aop.ApiAspect : ---------------------------------------------------------------------
方法之後執行....after.
方法執行完執行.....afterReturning
2017-02-14 15:23:42.286 INFO 2208 --- [nio-8080-exec-1] com.chhliu.springboot.aop.aop.ApiAspect : 耗時(毫秒) : 10
2017-02-14 15:23:42.289 INFO 2208 --- [nio-8080-exec-1] com.chhliu.springboot.aop.aop.ApiAspect : 傳回資料: "annotation"
2017-02-14 15:23:42.291 INFO 2208 --- [nio-8080-exec-1] com.chhliu.springboot.aop.aop.ApiAspect : ====================================================================>
由于Around環繞通知不比對,是以沒有切入進去!