之前项目中有个需求是记录用户的某些操作到数据库中。基本操作就是在每个需要保存操作日志的方法中都写上一个保存日志操作,但这样实现比较笨重,且不灵活,将业务代码和系统代码耦合在了一起。
如果我们写一个注解,标注了这个注解的方法就会记录调用了这个方法的人,并将方法的参数、方法名等信息保存起来,这样实现就比较轻便优雅。
Github 源码:https://github.com/cherispanty/demo.git
0、新建SpringBoot项目,省略~
1、引入Aspect依赖
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.7.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.0</version>
</dependency>
2、自定义MyLog注解
import java.lang.annotation.*;
@Target(ElementType.METHOD) //注解放置的目标位置,METHOD是可注解在方法级别上
@Retention(RetentionPolicy.RUNTIME) //注解在哪个阶段执行
@Documented //生成文档
public @interface MyLog {
String value() default "";
}
3、编写SysLogAspect织入类
import com.alibaba.fastjson.JSON;
import com.example.demo.annotation_demo.annotation.MyLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Component
@Aspect
public class SysLogAspect {
//将函数标记为切入点
@Pointcut("@annotation(com.example.demo.annotation_demo.annotation.MyLog)")
public void logPointCut() {
}
// 如果方法返回成功,则将函数标记为在切入点覆盖的方法之前执行的通知。
@AfterReturning("logPointCut()")
public void printLog(JoinPoint joinPoint) {
//从切面织入点处通过反射机制获取织入点处的方法
MethodSignature signature = (MethodSignature)joinPoint.getSignature();
//获取织入点所在的方法
Method method = signature.getMethod();
MyLog myLog = method.getAnnotation(MyLog.class);
String value = myLog.value(); //获取注解的value属性
//获取请求的类名
String name = joinPoint.getTarget().getClass().getName();
//获取请求的方法名
String methodName = method.getName();
Object[] args = joinPoint.getArgs();
String argsStr = JSON.toJSONString(args);
System.out.println("=========打印标注注解的信息===========");
System.out.println("获取注解的value属性:"+value);
System.out.println("获取请求的类名:"+name);
System.out.println("获取请求的方法名:"+methodName);
System.out.println("获取请求的参数:"+argsStr);
System.out.println("=========打印完毕===========");
}
}
4、编写controller实验
package com.example.demo.controller;
import com.example.demo.annotation_demo.annotation.MyLog;
import com.example.demo.bean.User;
import com.example.demo.dto.UserDTO;
import com.example.demo.form.UserForm;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
@RestController
public class TestController {
@MyLog("测试自定义注解")
@GetMapping("/hello")
public String hello(String name) {
return "你好"+name;
}
}
控制台打印:
拿到这些信息就可以做一些保存操作了