【Spring】SpringAop给所有Service增加日志

java 复制代码
@Component
@Aspect
@Slf4j
public class ServiceLogAop {

    @Pointcut("within(@org.springframework.stereotype.Service *)")
    public void serviceMethods() {
    }

    @Before(value = "serviceMethods()")
    public void logMethodEntry(JoinPoint joinPoint) {
        String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();

        if (args.length != 0) {
            try {
                log.info("========ServiceLog==Param======: " + className + "." + methodName + " with arguments: " + JSON.toJSONString(args));
            } catch (Exception e) {
                log.info("========ServiceLog==Param======: " + className + "." + methodName + " with arguments: " + Arrays.toString(args));
            }
        }
    }

    @AfterReturning(value = "serviceMethods()", returning = "result")
    public void logMethodExit(JoinPoint joinPoint, Object result) {
        String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();

        if (args.length != 0) {
            try {
                log.info("========ServiceLog==result======: " + className + "." + methodName + " with result: " + JSON.toJSONString(result));
            } catch (Exception e) {
                log.info("========ServiceLog==result======: error");
            }
        }
    }
}

其他的如controller同理

java 复制代码
@Pointcut("within(@org.springframework.stereotype.Service *) || within(@org.springframework.stereotype.Controller *)")

还可以排除

java 复制代码
@Pointcut("within(@org.springframework.stereotype.Service *) && !execution(* springfox.documentation.schema.property.*.*(..))")
相关推荐
间彧34 分钟前
SimpleDateFormat既然不推荐使用,为什么java 8+中不删除此类
java
金銀銅鐵36 分钟前
Spring 中的 initializeBean 方法的内部逻辑小总结
spring
间彧40 分钟前
DateTimeFormatter相比SimpleDateFormat在性能上有何差异?
java
间彧1 小时前
为什么说SimpleDateFormat是经典的线程不安全类
java
MacroZheng1 小时前
横空出世!MyBatis-Plus 同款 ES ORM 框架,用起来够优雅!
java·后端·elasticsearch
用户0332126663672 小时前
Java 查找并替换 Excel 中的数据:详细教程
java
间彧2 小时前
ThreadLocal实现原理与应用实践
java
若水不如远方2 小时前
Netty的四种零拷贝机制:深入原理与实战指南
java·netty
用户7493636848432 小时前
【开箱即用】一分钟使用java对接海外大模型gpt等对话模型,实现打字机效果
java
SimonKing2 小时前
一键开启!Spring Boot 的这些「魔法开关」@Enable*,你用对了吗?
java·后端·程序员