[英]Spring AOP change value of methods argument on around advice
是否可以在使用 Spring AOP 執行之前根據一些檢查更改方法參數值
我的方法
public String doSomething(final String someText, final boolean doTask) {
// Some Content
return "Some Text";
}
咨詢方法
public Object invoke(final MethodInvocation methodInvocation) throws Throwable {
String methodName = methodInvocation.getMethod().getName();
Object[] arguments = methodInvocation.getArguments();
if (arguments.length >= 2) {
if (arguments[0] instanceof String) {
String content = (String) arguments[0];
if(content.equalsIgnoreCase("A")) {
// Set my second argument as false
} else {
// Set my second argument as true
}
}
}
return methodInvocation.proceed();
}
請建議我設置方法參數值的方法,因為該參數沒有設置器選項。
是的,這是可能的。 您需要一個ProceedingJoinPoint
而不是:
methodInvocation.proceed();
然后,您可以使用新參數調用繼續,例如:
methodInvocation.proceed(new Object[] {content, false});
我使用MethodInvocation
得到了答案
public Object invoke(final MethodInvocation methodInvocation) throws Throwable {
String methodName = methodInvocation.getMethod().getName();
Object[] arguments = methodInvocation.getArguments();
if (arguments.length >= 2) {
if (arguments[0] instanceof String) {
String content = (String) arguments[0];
if(content.equalsIgnoreCase("A")) {
if (methodInvocation instanceof ReflectiveMethodInvocation) {
ReflectiveMethodInvocation invocation = (ReflectiveMethodInvocation) methodInvocation;
arguments[1] = false;
invocation.setArguments(arguments);
}
} else {
if (methodInvocation instanceof ReflectiveMethodInvocation) {
ReflectiveMethodInvocation invocation = (ReflectiveMethodInvocation) methodInvocation;
arguments[1] = true;
invocation.setArguments(arguments);
}
}
}
}
return methodInvocation.proceed();
}
您可以使用 Spring AOP,使用@Around
創建切入點。 然后您可以使用以下代碼根據條件更改方法的參數。
int index = 0;
Object[] modifiedArgs = proceedingJoinPoint.getArgs();
for (Object arg : proceedingJoinPoint.getArgs()) {
if (arg instanceof User) { // Check on what basis argument have to be modified.
modifiedArgs[index]=user;
}
index++;
}
return proceedingJoinPoint.proceed(modifiedArgs); //Continue with the method with modified arguments.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.