【问题标题】:Call aspect based on return value基于返回值调用方面
【发布时间】:2018-01-08 10:33:04
【问题描述】:

我正在使用 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方法?提前致谢。

【问题讨论】:

    标签: java aop spring-aop pointcut


    【解决方案1】:

    您可能会考虑抛出异常而不是从函数中返回错误值。如果你抛出异常,你可能会考虑做这样的事情。

    让我们再次重写您的函数。

    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
    }
    

    pointcut 和函数的参数只是举例。请根据需要修改它们。希望有帮助。

    【讨论】:

    • 感谢您的回答,但这不是我的解决方案。
    • 我支持这个解决方案,因为它返回的错误值不是 Java 或 OOP,它是在发明异常之前回到 C 和过程编程的糟糕旧时代。当然,您也可以在切入点中使用if() 限定符,但它也将在运行时进行评估,就像建议本身中的 if-else 代码一样。你有这个要求只是证明你的应用程序设计是完全错误的。
    【解决方案2】:

    我认为你可以将你的“if/else 逻辑”放在你的方法调用中,它可以从你的方法调用中获取结果,如果结果是“错误”,则返回,或者执行 else 逻辑。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-24
      • 2015-09-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多