java - 在 Spring Boot 应用程序中使用 AOP 记录方法调用及其参数

标签 java spring-boot logging aop spring-aop

而不是手动编写诸如

之类的代码
public void someMethod(Object someArg, Object otherArg) {
    logger.trace("someMethod invoked with arguments {}, {}", someArg, otherArg);    

    // method body
}

我想使用 AOP 自动生成这样的语句。有问题的应用是 Spring Boot 2.3.3 应用。

我认为不可能为使用 AOP 的 all 方法调用生成日志语句,仅适用于 Spring bean 上的方法调用。这对我目前的目的来说已经足够了。

有人能解释一下我如何向 Spring Boot 应用程序添加一个方面的具体步骤,该应用程序将为 Spring bean 上的所有方法调用生成一个如上所述的日志语句吗?如果切面只能拦截公共(public)方法调用,那就足够了。

最佳答案

确实,如果您使用基于代理的 Spring AOP 框架,您只能建议 Spring bean 的公共(public)方法(我个人认为这通常已经足够好了)。使用原生 AspectJ 编织,您可以建议任何方法。

首先,创建一个带有 @Aspect 注释的切面类,并使用 @component 进行组件扫描或声明为 @Bean你的配置。

然后,在类中,您需要一个切入点来定义建议的方法,以及一个告诉做什么的建议(例如,在您的案例中做一些日志记录)。

建议所有公共(public)方法或 Spring Bean 的切入点如下所示:

@Pointcut("execution(public * *(..))")
public void publicMethod() {}

或者,如果您只想记录服务方法,您可以使用:

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

建议可以在 (@Before)、(@After) 或两者 (@Around) 方法之前运行。对于日志记录,我会使用 @Around 建议。请注意,您还可以将切入点与逻辑运算符结合使用:

@Around("publicMethod() && withinService()")
public Object profileServiceMethods(ProceedingJoinPoint joinPoint) throws Throwable {
    // do some logging before method execution
    Object retVal = joinPoint.proceed();
    // and some logging after method execution
    return retVal;
}

你也可以看看我的即用型AOProfiling完整示例的 Spring Boot starter。

关于java - 在 Spring Boot 应用程序中使用 AOP 记录方法调用及其参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64571161/

相关文章:

java - 关于Java死锁情况的问题

java - 尝试在java中使用递归查找字符串的反向时出现StackOverflowError

java - 在 Java 中连接到 LDAP Active Directory,无需用户名和密码

spring-boot - @Query 不适用于 QueryDSL 谓词

java - Cloud Run 随机重启问题

java - Spring MVC 类型转换 : PropertyEditor or Converter?

java - Spring Boot 项目更新期间 Spring Data JPA 审计不起作用

c# - 不断增长的日志数据

kotlin - Kotlin 中的字符串模板和日志框架的占位符有什么区别?

java - 如何修改 net.schmizz.sshj 日志级别?