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

Ant*_*gos 5 java logging aop spring-aop spring-boot

而不是手动编写代码,例如

public void someMethod(Object someArg, Object otherArg) {
    logger.trace("someMethod invoked with arguments {}, {}", someArg, otherArg);    

    // method body
}
Run Code Online (Sandbox Code Playgroud)

我想使用 AOP 自动生成这样的语句。该应用程序是 Spring Boot 2.3.3 应用程序。

我认为不可能为使用 AOP 的所有方法调用生成日志记录语句,而只能为 Spring bean 上的方法调用生成日志记录语句。这对于我当前的目的来说已经足够了。

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

Dar*_*idl 8

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

首先,创建一个用 、 注释的方面类@Aspect,并用进行组件扫描或在配置中@component声明为。@Bean

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

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

@Pointcut("execution(public * *(..))")
public void publicMethod() {}
Run Code Online (Sandbox Code Playgroud)

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

@Pointcut("within(@org.springframework.stereotype.Service *)")
public void withinService() {}
Run Code Online (Sandbox Code Playgroud)

建议可以在您的方法之前 ( @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;
}
Run Code Online (Sandbox Code Playgroud)

您还可以查看我的即用型AOProfiling Spring Boot 启动器以获取完整示例。