一、添加aop starter依賴
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven./POM/4.0.0" xmlns:xsi="http://www./2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven./POM/4.0.0 http://maven./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>
二、配置文件中開啟支持
三、編寫切面
- 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容器,必須加入這個(gè)注解
- @Aspect // 該注解標(biāo)示該類為切面類,切面是由通知和切點(diǎn)組成的。
- 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.*(..))")// 定義切點(diǎn)表達(dá)式
- @Order(2)
- public void controllerPoint() {
- }
-
- @Pointcut("@annotation(com.chhliu.springboot.aop.annotation.RedisCache)")// 定義注解類型的切點(diǎn),只要方法上有該注解,都會匹配
- @Order(1)
- public void annotationPoint(){
-
- }
-
- // 定義前置通知
- @Before("annotationPoint()")
- public void before(JoinPoint joinPoint) {
- System.out.println("方法執(zhí)行前執(zhí)行.....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("響應(yīng)方法: " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
- logger.info("請求參數(shù) : " + Arrays.toString(joinPoint.getArgs()));
- logger.info("---------------------------------------------------------------------");
- startTime.set(System.currentTimeMillis());
- }
-
- @Around("controllerPoint() && args(arg)")// 需要匹配切點(diǎn)表達(dá)式,同時(shí)需要匹配參數(shù)
- public String around(ProceedingJoinPoint pjp, String arg) {
- System.out.println("name:"+arg);
- System.out.println("方法環(huán)繞start....around.");
- String result = null;
- try {
- result = (String) pjp.proceed()+" aop String";
- } catch (Throwable e) {
- e.printStackTrace();
- }
- System.out.println("方法環(huán)繞end.....around");
- return result;
- }
-
- @After("within(com.chhliu.springboot.aop.controller.*Controller)")
- public void after() {
- System.out.println("方法之后執(zhí)行....after.");
- }
-
- @AfterReturning(pointcut="controllerPoint()", returning="rst")
- public void afterReturning(JoinPoint joinPoint, Object rst) {
- System.out.println("方法執(zhí)行完執(zhí)行.....afterReturning");
- logger.info("耗時(shí)(毫秒) : " + (System.currentTimeMillis() - startTime.get()));
- logger.info("返回?cái)?shù)據(jù): {}", JSONUtils.toJSONString(rst));
- logger.info("====================================================================>");
- }
-
- @AfterThrowing("within(com.chhliu.springboot.aop.controller.*Controller)")
- public void afterThrowing() {
- System.out.println("異常出現(xiàn)之后.....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;
-
- /**
- * 描述:加入查詢結(jié)果的緩存
- * @author chhliu
- * 創(chuàng)建時(shí)間: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、啟動服務(wù)
2、在瀏覽器中輸入:http://localhost:8080/annotation
3、測試結(jié)果如下:
- 方法執(zhí)行前執(zhí)行.....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 : 響應(yīng)方法: 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 : 請求參數(shù) : []
- 2017-02-14 15:23:42.276 INFO 2208 --- [nio-8080-exec-1] com.chhliu.springboot.aop.aop.ApiAspect : ---------------------------------------------------------------------
- 方法之后執(zhí)行....after.
- 方法執(zhí)行完執(zhí)行.....afterReturning
- 2017-02-14 15:23:42.286 INFO 2208 --- [nio-8080-exec-1] com.chhliu.springboot.aop.aop.ApiAspect : 耗時(shí)(毫秒) : 10
- 2017-02-14 15:23:42.289 INFO 2208 --- [nio-8080-exec-1] com.chhliu.springboot.aop.aop.ApiAspect : 返回?cái)?shù)據(jù): "annotation"
- 2017-02-14 15:23:42.291 INFO 2208 --- [nio-8080-exec-1] com.chhliu.springboot.aop.aop.ApiAspect : ====================================================================>
由于Around環(huán)繞通知不匹配,所以沒有切入進(jìn)去!
|