java - 根据返回值调用切面

标签 java aop spring-aop pointcut

我正在使用 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/

相关文章:

java - 在另一个方法中调用一个方法后执行一些操作

java - 具有特定注释的参数的方法的 AspectJ 切入点

java - JMS 无法连接到 websphere mq

c# - 我没有源代码的程序集上的 PostSharp

Java LSt 默认和修改列表

.net - .Net 中 AOP 的最佳实现是什么?

java - 使用 Spring AOP 记录是个好主意吗?

java - 如何使用spring aop自动设置date_created

java - "|="操作在 C++ 中是什么意思?

java - 我正在尝试创建一个 MVP(最小可行产品)。 Google App Engine 是一个很好用的框架吗?