概述
项目中我们经常会用到aop切面,比如日志记录,事务管理等。
依赖
1 2 3 4
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
|
自定义切面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| package com.qn.interceptor;
import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.*; 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 javax.servlet.http.HttpServletRequest; import java.util.Arrays;
@Aspect @Component @Order(1) public class LogAspect {
Logger logger = LoggerFactory.getLogger(LogHandlerInterceptor.class);
ThreadLocal<Long> startTime = new ThreadLocal<>();
@Pointcut("execution(public * com.qn.controller..*.*(..))") public void webLog() { }
@Before("webLog()") public void doBefore(JoinPoint joinPoint) { startTime.set(System.currentTimeMillis()); ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = requestAttributes.getRequest();
logger.info("Aspect-URL: " + request.getRequestURI().toLowerCase()); logger.info("Aspect-HTTP_METHOD: " + request.getMethod()); logger.info("Aspect-IP: " + request.getRemoteAddr()); logger.info("Aspect-REQUEST_METHOD: " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); logger.info("Aspect-Args: " + Arrays.toString(joinPoint.getArgs())); }
@After("webLog()") public void doAfter() {
}
@AfterReturning(returning = "ret", pointcut = "webLog()") public void doAfterReturning(Object ret) throws Throwable { logger.info("Aspect-Response: " + ret); Long endTime = System.currentTimeMillis(); logger.info("Aspect-SpeedTime: " + (endTime - startTime.get()) + "ms"); }
}
|
测试
启动 访问: