而不是手动编写诸如
之类的代码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/