1、自定义注解
/**
* 自定义操作日志注解
* @author arli
*/
//METHOD是可注解在方法级别上
@Target(ElementType.METHOD)
//注解在哪个阶段执行,会被编译在class文件中,可以被反射读取
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CarOperation {
// 用户的操作详情(接口实现的操作)
String operation() default "";
}
2、AOP切面
/**
* 设置操作日志切入点 记录操作日志 在注解的位置切入代码
*/
@Pointcut("@annotation(com.jsy.community.util.CarOperation)")
public void operLogPoinCut() {
}
/**
* 正常返回通知,拦截用户操作日志,连接点正常执行完成后执行, 如果连接点抛出异常,则不会执行
* @param joinPoint 切入点
* @param keys 返回结果
*/
// value:上面切点的方法名 returning :指定返回值key
//AfterReturning:指定AOP切面在注解方法执行完成之后 执行以下代码
@AfterReturning(value = "operLogPoinCut()", returning = "keys")
@Login//自定义的登录注解,可通过UserUtils获取用户id
public void saveOperLog(JoinPoint joinPoint, Object keys) {
System.out.println("进入aop");
//创建的日志接受对象
CarOperationLog carOperationLog = new CarOperationLog();
// 从切面织入点处通过反射机制获取织入点
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
// 获取切入点所在的方法
Method method = signature.getMethod();
//获取用户id
String userId = UserUtils.getUserId();
//根据用户id查到角色id
Long roleId = adminUserRoleService.selectRoleIdByUserId(userId);
// 获取操作
try {
//方法如果存在这样的注释,则返回指定类型的元素的注释,否则为null。
//ps:方法如果存在@CarOperation注解则返回 注释(operation),也就是用户操作详情
CarOperation annotation = method.getAnnotation(CarOperation.class);
if (annotation != null) {//判断不为空的
System.out.println("对象开始赋值");
//获取设置的用户操作详情
String operation = annotation.operation();
System.out.println("aop获取的userRole" + roleId);
System.out.println("aop获取的operation" + operation);
carOperationLog.setUserRole(roleId); // 操作角色id
carOperationLog.setOperation(operation);//操作
carOperationLog.setStatus(0); // 状态
carOperationLog.setOperationTime(LocalDateTime.now());
carOperationLog.setDeleted(0L);
System.out.println("对象结束赋值");
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("开始保存");
boolean save = carOperationService.save(carOperationLog);
if (save) {
carOperationLog.setStatus(1); // 状态
}
}