使用Spring AOP获取方法参数? [英] Get method arguments using Spring AOP?
问题描述
我正在使用Spring AOP并具有以下方面:
I am using Spring AOP and have below aspect:
@Aspect
public class LoggingAspect {
@Before("execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..))")
public void logBefore(JoinPoint joinPoint) {
System.out.println("logBefore() is running!");
System.out.println("hijacked : " + joinPoint.getSignature().getName());
System.out.println("******");
}
}
以上方面拦截 addCustomer
方法执行。 addCustomer
方法将字符串作为输入。
但我需要在 logBefore
方法中记录传递给 addCustomer
方法的输入。
是否可以这样做?
Above aspect intercepts addCustomer
method execution. addCustomer
method takes string as an input.
But I need to log input passed to addCustomer
method inside logBefore
method.
Is it possible to do so ?
推荐答案
您有几个选择:
首先,您可以使用 JoinPoint#getArgs()
方法,它返回包含所有参数的 Object []
建议的方法。您可能需要进行一些投射,具体取决于您对它们的处理方式。
First, you can use the JoinPoint#getArgs()
method which returns an Object[]
containing all the arguments of the advised method. You might have to do some casting depending on what you want to do with them.
其次,您可以使用 args
切入点表达式如下:
Second, you can use the args
pointcut expression like so:
// use '..' in the args expression if you have zero or more parameters at that point
@Before("execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..)) && args(yourString,..)")
然后您的方法可以定义为
then your method can instead be defined as
public void logBefore(JoinPoint joinPoint, String yourString)
这篇关于使用Spring AOP获取方法参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!