Controller
java
@PostMapping("/test")
@LogAnnotation(module = "springboot",description = "测试")
public void addNum(User user) {
}
自定义注解
```java @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface LogAnnotation {
String module() default ""; // 模块名
String description() default ""; // 描述
}
```
AOP实现
```java @Slf4j @Aspect @Component public class LogAspect {
@Before(" @annotation(LogAnnotation) ")
private void recordLog(JoinPoint pjp) throws NoSuchMethodException {
Class<?> clazz = pjp.getTarget().getClass();
String clazzName = clazz.getName(); // 类名
String methodName = pjp.getSignature().getName(); //方法名
Object[] objs = pjp.getArgs();
String args = JSONObject.toJSONString(objs);
LogAnnotation annotation = getAnnotation(pjp); // 获取注解
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
System.out.println("模块:"+annotation.module()+"\n描述:"+annotation.description() +
"\n类:"+clazzName + "\n方法:"+methodName+"\n参数:"+args+
"\nURL:"+request.getRequestURL());
}
// 通过反射获取LogAnnotation注解
private LogAnnotation getAnnotation(JoinPoint joinPoint){
MethodSignature signature = (MethodSignature)joinPoint.getSignature();
return signature.getMethod().getAnnotation(LogAnnotation.class);
}
} ```
本文介绍如何在Spring Boot项目中使用AOP实现自定义注解LogAnnotation,记录方法调用的日志,包括模块名、描述、类名、方法名和参数。
449

被折叠的 条评论
为什么被折叠?



