先自定义一个注解
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogSelf {
// 方法名称
String methodName() default "";
// 当前操作人
String currentUser() default "";
// 操作
String operate() default "";
}
定义一个切面类
@Slf4j
@Aspect
@Component
public class LogAspect {
@Autowired
private AspectUtil aspectUtil;
@Autowired
private LogService logService;
// 定义一个切入点
@Pointcut("@annotation(com.tinady.annotation.MyOperationLog)")
public void doPointcut() {
log.info("进入切入点~~~");
}
// 定义一个通知
@Before("doPointcut()")
public void doBefore(JoinPoint joinPoint) {
log.info("进入前置通知");
doHandlerLog(joinPoint);
}
// 日志记录处理
private void doHandlerLog(JoinPoint joinPoint) {
// 获取自定义注解@MyOperationLog
MyOperationLog myOperationLog = aspectUtil.getMyOperationLogByJoinPoint(joinPoint);
if (null == myOperationLog) {
return;
}
// 获取签名
String signature = joinPoint.getSignature().toString();
// 获取方法名
String methodName = signature.substring(signature.lastIndexOf(".") + 1, signature.indexOf("("));
// 获取方法的execution
String longTemp = joinPoint.getStaticPart().toLongString();
String classType = joinPoint.getTarget().getClass().getName();
try {
Class<?> clazz = Class.forName(classType);
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(MyOperationLog.class) && method.getName().equals(methodName)) {
// 解析
MyOperationLogVo myOperationLogVos = parseAnnotation(method);
// 日志添加
logService.addLog(myOperationLogVos);
}
}
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
// 解析方法上注解中的值
public MyOperationLogVo parseAnnotation(Method method) {
MyOperationLog myOperationLog = method.getAnnotation(MyOperationLog.class);
if (null == myOperationLog) {
return null;
}
MyOperationLogVo myOperationLogVo = new MyOperationLogVo();
myOperationLogVo.setMethodName(myOperationLog.methodName());
myOperationLogVo.setCurrentUser(myOperationLog.currentUser());
myOperationLogVo.setOperate(myOperationLog.operate());
return myOperationLogVo;
}
}
Util
@Component
public class AspectUtil {
/**
*
* 功能描述:通过JoinPoint获取注解MyOperationLog
*
* 访问目标方法参数,有三种方法(实际有四种):
* 1.joinpoint.getargs():获取带参方法的参数
* 2.joinpoint.getTarget():.获取他们的目标对象信息
* 3.joinpoint.getSignature():(signature是信号,标识的意思):获取被增强的方法相关信息
*
*/
public MyOperationLog getMyOperationLogByJoinPoint(JoinPoint joinPoint) {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (null == method) {
return null;
}
return method.getAnnotation(MyOperationLog.class);
}
}
使用
@RestController
@RequestMapping("/aop")
public class AopController {
@GetMapping("/tetLog")
@MyOperationLog(methodName = "testLog", currentUser = "admin", operate = "查询")
public String testLog() {
return "Log";
}
}