使用aspectj的Spring AOP - 如何记录内部方法?如何在方面类中包含最终方法调用?在AOP中进行适当的异常处理

时间:2017-03-24 05:43:05

标签: spring-boot spring-aop

我使用Spring AOP进行日志记录服务并遇到3个问题,

  1. 内部方法记录 参考代码:How to Log all the methods public method calls in AOP

  2. 在代理中包含最终方法 遵循pmd,checkstyle和findbug中提到的代码标准,我们无法更改方法的final关键字。我尝试了接口并连接到调用但不起作用。

  3. 处理异常,之后返回服务本身以获取实际响应

    @RestController(/person) public Person getpersonInfo(){ try{ ...... getValidPerson(); return response;/* Response including Person Info*/ } catch (Exception ex) { return response; /*Response stating the exception Condition*/ } }

  4. 请提供您宝贵的建议

1 个答案:

答案 0 :(得分:0)

  1. 如果您正在谈论self-invocation,例如this.someOtherMethod()(在没有this.的情况下是相同的),则它不起作用,因为您没有使用代理。因此,要么将Spring配置为公开代理对象,要么在调用方法之前手动获取对代理的引用,要么从Spring AOP切换到AspectJ with load-time weaving

  2. 代理在技术上在运行时生成子类。但是最终的类不能被扩展,最终的方法也不能被覆盖。因此,您无法使用代理处理它们。再说一遍,如果你认为你需要这个,请切换到完整的AspectJ。

  3. 这可以通过@Around这样的建议来完成:

  4. @Around("... your pointcut ...")
    public Object myAdvice(final ProceedingJoinPoint thisJoinPoint) throws Throwable {
        System.out.println(thisJoinPoint);
        try {
            return thisJoinPoint.proceed();
        }
        catch (Exception e) {
            e.printStackTrace();
            return "some other object";
        }
    }