背景
在工作中需要在controller里记录日志以及前台传递来的参数等,如果每个controller都需要使用slf4j去记录的话,
会显得代码太冗余。因此使用aop来解决此问题。话不多说,直接上代码!
POM文件
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-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>
如果是使用idea直接生成的pom文件别忘了此处添加上aop的依赖
service层
/**
* @author zxw
* @version 1.0
* @description 业务接口
* @data: 2020/2/15 20:22
*/
public interface DogService {
void say();
}
/实现类
/**
* @author zxw
* @version 1.0
* @description 业务实现类
* @data: 2020/2/15 20:22
*/
@Service
public class DogServiceImpl implements DogService {
@Override
public void say() {
System.out.println("在汪汪叫===");
}
}
重点的配置类(springboot中around和AfterThrowing有冲突(版本问题),如果需要捕捉异常使用after和before)
package cn.zxw.config;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
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.lang.reflect.Method;
import java.security.Principal;
import java.util.Arrays;
import java.util.List;
/**
* @author zxw
* @version 1.0
* @description aop配置类
* @data: 2020/2/15 18:13
*/
@Aspect
@Component
public class AspectConfig {
@Pointcut("execution(public * cn.zxw.controller.*.*(..))")
public void logMsg() {
System.out.println("log=======");
}
@Before("logMsg()")
public void before(JoinPoint joinPoint) {
System.out.println("before====");
}
@After("logMsg()")
public void after(JoinPoint point) {
System.out.println("after===");
}
@AfterReturning(value = "logMsg()", returning = "ret")
public void afterReturning() {
System.out.println("AfterReturning====");
}
@AfterThrowing(pointcut = "logMsg()", throwing = "ex")
public void doAfterThrowing(JoinPoint point, Exception ex) {
String methodName = point.getSignature().getName();
List<Object> args = Arrays.asList(point.getArgs());
System.out.println("连接点方法为:" + methodName + ",参数为:" + args + ",异常为:" + ex);
}
@Around("logMsg()")
public Object around(ProceedingJoinPoint joinPoint) {
System.out.println("around====");
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
Object result = null;
try {
result = joinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
//以下代码看业务需求可以曲joinPoint或request里的数据
Signature signature = joinPoint.getSignature();
Object[] args = joinPoint.getArgs();
String method1 = request.getMethod();
Principal userPrincipal = request.getUserPrincipal();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
long endTime = System.currentTimeMillis();
return result;
}
}
此处要注意的是如果用的是around的话joinPoint.proceed();是必须要有的,不能直接输出一句话。这要的话导致controller里的代码不会执行。
controller
package cn.zxw.controller;
import cn.zxw.bean.Dog;
import cn.zxw.service.DogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author zxw
* @version 1.0
* @description aop测试
* @data: 2020/2/15 17:23
*/
@RestController
@RequestMapping("/aop")
public class AopController {
@Autowired
private DogService dogService;
@PostMapping("/test")
public String test(Integer flag) {
dogService.say();
if (flag == 1) {
throw new RuntimeException("1111");
}
return "success";
}
}
输出结果
发生异常的时输出的结果