我正在使用 Spring AOP。这是示例方法:
public String method(List<Integer> ids) {
if(ids == null) return "ERROR";
else return "OK";
}
我的外观是这样的:
@AfterReturning(pointcut = "execution( * com.pack.MyService.method(..))", returning = "result")
public void methodAdvice(JoinPoint joinPoint, String result) {
// My implementation
}
是否可以根据method()
的返回值来调用或不调用aspect方法?提前致谢。
最佳答案
您可能会考虑抛出异常,而不是从函数返回错误值。如果您抛出异常,您可能会考虑做这样的事情。
让我们再次重写您的函数。
public String method(List<Integer> ids) throws Exception {
if(ids == null)
throw new RunTimeException("ERROR");
return "OK";
}
现在你的方面可能看起来像这样。
@AfterThrowing(pointcut = "class() && execution( * com.pack.MyService.method(..))", throwing = "ex")
public void onMethodExecutionFailure(Exception ex) {
log.debug(ex.getMessage());
// Your implementation
}
@AfterReturning(pointcut = "execution( * com.pack.MyService.method(..))")
public void onMethodExecutionSuccess(String result) {
log.debug("Success!");
// Your success implementation
}
函数的切入点
和参数只是示例。请根据您的需要修改它们。希望有帮助。
关于java - 根据返回值调用切面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48148470/