AspectJ作为语言级别的AOP框架,功能相比于SpringAOP更加强大。SpringAOP旨在提供给用户一个轻量级的AOP实现方案,它只能应用在SpringIOC容器中管理的bean。而AspectJ旨在提供给用户一个完整的AOP解决方案,它可以应用在所有的域对象中,下面给大家介绍SpringBoot使用Aspect切面拦截打印请求参数的代码。
引入依赖
1
2
3
4
|
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
|
也用到了fastjson打印参数 , 如果引了就不需要(也可以根据自己的来打印)
1
2
3
4
5
6
|
<!-- 添加fastjson 支持 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version> 1.2 . 15 </version>
</dependency>
|
LogAspect.java
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
|
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
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;
/**
* @author zhipeih
* @date 2021/07/14
*/
@Slf4j
@Component
@Aspect //表示它是一个切面
public class LogAspect {
/**
*
* execution:改成自己要打印的控制器路径
* @param proceedingJoinPoint
* @return
* @throws Throwable
*/
@Around ( "execution(* com.example.*.controller.*.*(..)) " )
public Object handleControllerMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
//原始的HTTP请求和响应的信息
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
Signature signature = proceedingJoinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature)signature;
//获取当前执行的方法
Method targetMethod = methodSignature.getMethod();
//获取参数
Object[] objects = proceedingJoinPoint.getArgs();
//获取返回对象
Object object = proceedingJoinPoint.proceed();
StringBuilder sb = new StringBuilder( 1000 );
sb.append( "-------------------------------------------------------------\n" );
sb.append( "Controller: " ).append(targetMethod.getDeclaringClass().getName()).append( "\n" );
sb.append( "Method : " ).append(targetMethod.getName()).append( "\n" );
sb.append( "Params : " ).append(JSON.toJSONString(objects)).append( "\n" );
sb.append( "URI : " ).append(request.getRequestURI()).append( "\n" );
sb.append( "URL : " ).append(request.getRequestURL()).append( "\n" );
sb.append( "Return : " ).append(object).append( "\n" );
sb.append( "-------------------------------------------------------------\n" );
System.out.println(sb);
return proceedingJoinPoint.proceed();
}
}
|
到此这篇关于SpringBoot使用Aspect切面拦截打印请求参数的文章就介绍到这了,更多相关SpringBoot打印请求参数内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://www.cnblogs.com/pxblog/p/15011186.html