springboot自定义log注解支持EL表达式

本文涉及的产品
日志服务 SLS,月写入数据量 50GB 1个月
简介: springboot自定义log注解支持EL表达式

一、自定义注解

package com.xxxx.common.aop;
 
 
 
import com.xxx.common.enums.OperationLogModuleEnum;
 
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
/**
 * 自定义操作日志记录注解
 *
 * @author minos
 */
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {
    /**
     * 模块
     */
    public OperationLogModuleEnum module() default OperationLogModuleEnum.USER_MANGER;
 
    /**
     * 描述
     */
    public String describe() default "";
 
    /**
     * 操作人类别
     */
    public String parameter() default "";
}

二、EL表达式支持

package com.xxxxx.common;
 
 
public class ExpressionRootObject {
    private final Object object;
    private final Object[] args;
 
    public ExpressionRootObject(Object object, Object[] args) {
        this.object = object;
        this.args = args;
    }
 
    public Object getObject() {
        return object;
    }
 
    public Object[] getArgs() {
        return args;
    }
}
package com.xxx.common;
import org.springframework.aop.support.AopUtils;
import org.springframework.context.expression.AnnotatedElementKey;
import org.springframework.context.expression.CachedExpressionEvaluator;
import org.springframework.context.expression.MethodBasedEvaluationContext;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
 
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
 
public class ExpressionEvaluator<T> extends CachedExpressionEvaluator {
    private final ParameterNameDiscoverer paramNameDiscoverer = new DefaultParameterNameDiscoverer();
    private final Map<ExpressionKey, Expression> conditionCache = new ConcurrentHashMap<>(64);
    private final Map<AnnotatedElementKey, Method> targetMethodCache = new ConcurrentHashMap<>(64);
 
 
    public EvaluationContext createEvaluationContext(Object object, Class<?> targetClass, Method method, Object[] args) {
        Method targetMethod = getTargetMethod(targetClass, method);
        ExpressionRootObject root = new ExpressionRootObject(object, args);
        return new MethodBasedEvaluationContext(root, targetMethod, args, this.paramNameDiscoverer);
    }
 
 
    public T condition(String conditionExpression, AnnotatedElementKey elementKey, EvaluationContext evalContext, Class<T> clazz) {
        return getExpression(this.conditionCache, elementKey, conditionExpression).getValue(evalContext, clazz);
    }
 
    private Method getTargetMethod(Class<?> targetClass, Method method) {
        AnnotatedElementKey methodKey = new AnnotatedElementKey(method, targetClass);
        Method targetMethod = this.targetMethodCache.get(methodKey);
        if (targetMethod == null) {
            targetMethod = AopUtils.getMostSpecificMethod(method, targetClass);
            if (targetMethod == null) {
                targetMethod = method;
            }
            this.targetMethodCache.put(methodKey, targetMethod);
        }
        return targetMethod;
    }
}

三、定义aop

package com.xxxx.common.aspect;
 
import com.xxxx.common.ExpressionEvaluator;
import com.xxxx.common.aop.Log;
import com.xxxx.common.utils.CurrentUserUtil;
import com.xxxx.common.utils.IpUtils;
import com.xxxx.common.utils.ServletUtils;
import com.xxxx.model.OperationLog;
import com.xxxx.service.OperationLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.expression.AnnotatedElementKey;
import org.springframework.expression.EvaluationContext;
import org.springframework.stereotype.Component;
 
import java.lang.reflect.Method;
 
/**
 * 操作日志记录处理
 *
 * @author minos
 */
@Aspect
@Component
public class LogAspect {
    @Autowired
    OperationLogService operationLogService;
    private ExpressionEvaluator<String> evaluator = new ExpressionEvaluator<>();
 
    private static final Logger log = LoggerFactory.getLogger(LogAspect.class);
 
    /**
     * 配置织入点
     */
    @Pointcut("@annotation(com.lets.psccs.common.aop.Log)")
    public void logPointCut() {
    }
 
    /**
     * 处理完请求后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
    public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
        handleLog(joinPoint);
    }
 
    /**
     * 拦截异常操作
     *
     * @param joinPoint 切点
     * @param e         异常
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint);
    }
 
    protected void handleLog(final JoinPoint joinPoint) {
        addOPerationLog(joinPoint);
    }
 
    /**
     * 写入日志
     * @param joinPoint
     */
    private void addOPerationLog(JoinPoint joinPoint) {
        try {
            // 获得注解
            Log myLog = getAnnotationLog(joinPoint);
            if (myLog == null) {
                return;
            }
 
          // 请求的地址
            String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
            String modelName = myLog.module().getName();
            String parameter = getParameter(joinPoint);
            String describe = myLog.describe().replace("parameter",parameter);
            OperationLog operationLog=new OperationLog(CurrentUserUtil.currentUser());
            operationLog.setModule(modelName);
            operationLog.setIp(ip);
            operationLog.setContent(describe);
            operationLogService.insertSelective(operationLog);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    private String getParameter(JoinPoint joinPoint) {
        Log handler = null;
        try {
            handler = getAnnotationLog(joinPoint);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (joinPoint.getArgs() == null) {
            return null;
        }
        EvaluationContext evaluationContext = evaluator.createEvaluationContext(joinPoint.getTarget(), joinPoint.getTarget().getClass(), ((MethodSignature) joinPoint.getSignature()).getMethod(), joinPoint.getArgs());
        AnnotatedElementKey methodKey = new AnnotatedElementKey(((MethodSignature) joinPoint.getSignature()).getMethod(), joinPoint.getTarget().getClass());
        return evaluator.condition(handler.parameter(), methodKey, evaluationContext, String.class);
    }
    /**
     * 是否存在注解,如果存在就获取
     */
    private Log getAnnotationLog(JoinPoint joinPoint) throws Exception {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
 
        if (method != null) {
            return method.getAnnotation(Log.class);
        }
        return null;
    }
}
 

四、使用

 /**
     * 更新用户信息
     *
     * @param userVo
     * @return
     */
    @PostMapping("/update")
    @ApiOperation("更新用户信息")
    @Check({AuthorityConsts.XiTongSheZhi.BJYH})
    @Log(module = OperationLogModuleEnum.USER_MANGER,describe ="编辑了parameter用户信息",parameter = "{#userVo.id}")
    public AjaxResult update(@RequestBody @Validated UserVO userVo) {
        User user = new User();
        BeanUtils.copyProperties(userVo, user);
        int update = userService.update(user);
        return toAjax(update);
    }

五、效果

相关实践学习
通过日志服务实现云资源OSS的安全审计
本实验介绍如何通过日志服务实现云资源OSS的安全审计。
相关文章
|
13天前
|
缓存 监控 Java
SpringBoot @Scheduled 注解详解
使用`@Scheduled`注解实现方法周期性执行,支持固定间隔、延迟或Cron表达式触发,基于Spring Task,适用于日志清理、数据同步等定时任务场景。需启用`@EnableScheduling`,注意线程阻塞与分布式重复问题,推荐结合`@Async`异步处理,提升任务调度效率。
277 127
|
28天前
|
XML 安全 Java
使用 Spring 的 @Aspect 和 @Pointcut 注解简化面向方面的编程 (AOP)
面向方面编程(AOP)通过分离横切关注点,如日志、安全和事务,提升代码模块化与可维护性。Spring 提供了对 AOP 的强大支持,核心注解 `@Aspect` 和 `@Pointcut` 使得定义切面与切入点变得简洁直观。`@Aspect` 标记切面类,集中处理通用逻辑;`@Pointcut` 则通过表达式定义通知的应用位置,提高代码可读性与复用性。二者结合,使开发者能清晰划分业务逻辑与辅助功能,简化维护并提升系统灵活性。Spring AOP 借助代理机制实现运行时织入,与 Spring 容器无缝集成,支持依赖注入与声明式配置,是构建清晰、高内聚应用的理想选择。
276 0
|
1月前
|
Java 测试技术 API
将 Spring 的 @Embedded 和 @Embeddable 注解与 JPA 结合使用的指南
Spring的@Embedded和@Embeddable注解简化了JPA中复杂对象的管理,允许将对象直接嵌入实体,减少冗余表与连接操作,提升数据库设计效率。本文详解其用法、优势及适用场景。
214 126
|
2月前
|
XML JSON Java
Spring框架中常见注解的使用规则与最佳实践
本文介绍了Spring框架中常见注解的使用规则与最佳实践,重点对比了URL参数与表单参数的区别,并详细说明了@RequestParam、@PathVariable、@RequestBody等注解的应用场景。同时通过表格和案例分析,帮助开发者正确选择参数绑定方式,避免常见误区,提升代码的可读性与安全性。
|
14天前
|
XML Java 数据格式
常用SpringBoot注解汇总与用法说明
这些注解的使用和组合是Spring Boot快速开发和微服务实现的基础,通过它们,可以有效地指导Spring容器进行类发现、自动装配、配置、代理和管理等核心功能。开发者应当根据项目实际需求,运用这些注解来优化代码结构和服务逻辑。
115 12
|
27天前
|
Java 测试技术 数据库
使用Spring的@Retryable注解进行自动重试
在现代软件开发中,容错性和弹性至关重要。Spring框架提供的`@Retryable`注解为处理瞬时故障提供了一种声明式、可配置的重试机制,使开发者能够以简洁的方式增强应用的自我恢复能力。本文深入解析了`@Retryable`的使用方法及其参数配置,并结合`@Recover`实现失败回退策略,帮助构建更健壮、可靠的应用程序。
107 1
使用Spring的@Retryable注解进行自动重试
|
20天前
|
缓存 Java 应用服务中间件
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
本文详解Spring Boot十大核心配置优化技巧,涵盖Tomcat连接池、数据库连接池、Jackson时区、日志管理、缓存策略、异步线程池等关键配置,结合代码示例与通俗解释,助你轻松掌握高并发场景下的性能调优方法,适用于实际项目落地。
218 4
|
27天前
|
传感器 Java 数据库
探索Spring Boot的@Conditional注解的上下文配置
Spring Boot 的 `@Conditional` 注解可根据不同条件动态控制 Bean 的加载,提升应用的灵活性与可配置性。本文深入解析其用法与优势,并结合实例展示如何通过自定义条件类实现环境适配的智能配置。
探索Spring Boot的@Conditional注解的上下文配置
|
27天前
|
智能设计 Java 测试技术
Spring中最大化@Lazy注解,实现资源高效利用
本文深入探讨了 Spring 框架中的 `@Lazy` 注解,介绍了其在资源管理和性能优化中的作用。通过延迟初始化 Bean,`@Lazy` 可显著提升应用启动速度,合理利用系统资源,并增强对 Bean 生命周期的控制。文章还分析了 `@Lazy` 的工作机制、使用场景、最佳实践以及常见陷阱与解决方案,帮助开发者更高效地构建可扩展、高性能的 Spring 应用程序。
Spring中最大化@Lazy注解,实现资源高效利用