aspect

add an aspect in Spring Boot

Maven

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>

Enable/disable auto configuration

  • property.properties
1
spring.aop.auto = true    //'false' disables the auto configuration

Creating aspects with @Aspect

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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package com.uuzu.newbasys.aspect;

import java.io.BufferedReader;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import com.uuzu.newbasys.annotation.LogAPIAccessAnnotation;
import com.uuzu.newbasys.mapper.ba.log.LogAPIAccessMapper;
import com.uuzu.newbasys.model.log.LogAPIAccessModel;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Aspect
@Component
public class LogAPIAccessAspect {

private static final Logger logger = LoggerFactory.getLogger(LogAPIAccessAspect.class);

@Autowired
private LogAPIAccessMapper mapper;

@Autowired
private HttpServletRequest request;

ThreadLocal<LogAPIAccessModel> logModelTh = new ThreadLocal<>();

@Around("@annotation(com.uuzu.newbasys.annotation.LogAPIAccessAnnotation)")
public Object logAPIAccess(ProceedingJoinPoint joinPoint) throws Throwable {

LogAPIAccessModel logModel = new LogAPIAccessModel();
logModelTh.set(logModel);

// username
String userName = "anonymous";

if (SecurityContextHolder.getContext().getAuthentication() != null) {
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication()
.getPrincipal();
userName = userDetails.getUsername();
}

// 记录下请求内容
String url = request.getRequestURL().toString();
String httpMethod = request.getMethod();
String ip = request.getRemoteAddr();

MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
Method method = methodSignature.getMethod();
// 类名
String className = methodSignature.getDeclaringTypeName();
// 方法名
String methodName = methodSignature.getName();
// 路径参数
JSONObject params = new JSONObject(request.getParameterMap());
// requestBody
StringBuilder sb = new StringBuilder();
BufferedReader reader = request.getReader();
try {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} finally {
reader.close();
}
String requestBody = null;
if (sb.toString().length() > 0) {
requestBody = sb.toString();
}

long start = System.currentTimeMillis();

Object proceed = joinPoint.proceed();

// 执行时间
long executionTime = System.currentTimeMillis() - start;

// 注解上的描述信息
LogAPIAccessAnnotation logAnnotation = method.getAnnotation(LogAPIAccessAnnotation.class);
String logAnnotationValue = "-";
if (logAnnotation != null) {
logAnnotationValue = logAnnotation.value();
}
String[] logAnnotationValueArray = logAnnotationValue.split("-");

logModel.setUserName(userName);
logModel.setProject(logAnnotationValueArray[0]);
logModel.setPage(logAnnotationValueArray[1]);
logModel.setDetail(logAnnotationValueArray[2]);
logModel.setHttpMethod(httpMethod);
logModel.setUrl(url);
logModel.setExecutionTime(executionTime);
logModel.setParams(params.toString());
logModel.setRequestBody(requestBody);
logModel.setClassName(className);
logModel.setMethodName(methodName);
logModel.setIp(ip);

return proceed;
}

@AfterReturning(pointcut = "@annotation(com.uuzu.newbasys.annotation.LogAPIAccessAnnotation)", returning = "response")
public void doAfterReturning(Object response) throws Throwable {

// 处理完请求,返回内容
LogAPIAccessModel logModel = logModelTh.get();
logModel.setResponse(response.toString());

try {
mapper.save(logModel);
} catch (Exception e) {
logger.error("接口统计报错!");
logger.error(e.getMessage());
} finally {
logModelTh.remove();
}
}
}

create annotation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.uuzu.newbasys.annotation;

import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogAPIAccessAnnotation {
// value 格式为 page-detail
// 实时运营商-搜索
String value() default "";
}

test

1
2
3
4
5
6
7
@PostMapping("/logPostMethodTest")
@LogAPIAccessAnnotation("yoobi-test-log")
public Map<String, Object> logPostMethodTest(@RequestBody Map<String, Object> requestBody,@RequestParam("name") String name,
@RequestParam("age") int age) {

return requestBody;
}

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×