在 Spring AOP 中使用 @AfterReturning 从 class 修改值

Modify value from class with @AfterReturning in Spring AOP

如何使用@AfterReturning 建议修改值,它适用于除 String 之外的任何对象。我知道 String 是不可变的。以及如何修改字符串而不更改 AccountDAO class 中 saveEverything() 函数的返回类型? 这是代码片段:

@Component
public class AccountDAO {
    public String saveEverything(){
        String save = "save";
        return save;
    }
}

和看点:

@Aspect
@Component
public class AfterAdviceAspect {
    @AfterReturning(pointcut = "execution(* *.save*())", returning = "save")
    public void afterReturn(JoinPoint joinPoint, Object save){
        save = "0";
        System.out.println("Done");
    }
}

和主要应用程序:

public class Application {
public static void main(String[] args) {
    AnnotationConfigApplicationContext context =
            new AnnotationConfigApplicationContext(JavaConfiguration.class);

    AccountDAO accountDAO = context.getBean("accountDAO", AccountDAO.class);

    System.out.println(">"+accountDAO.saveEverything());;

    context.close();
  }
}

来自文档:After Returning Advice

Please note that it is not possible to return a totally different reference when using after returning advice.

正如 anavaras lamurep 在评论中正确指出的那样,@Around 建议可用于实现您的要求。一个示例方面如下

@Aspect
@Component
public class ExampleAspect {
    @Around("execution(* com.package..*.save*()) && within(com.package..*)")
    public String around(ProceedingJoinPoint pjp) throws Throwable {
        String rtnValue = null;
        try {
            // get the return value;
            rtnValue = (String) pjp.proceed();
        } catch(Exception e) {
            // log or re-throw the exception 
        }
        // modify the return value
        rtnValue = "0";
        return rtnValue;
    }
}

请注意问题中给出的切入点表达式是全局的。此表达式将匹配对以 save 开头并返回 Object 的任何 spring bean 方法的调用。这可能会产生不良结果。建议将 类 的范围限制在 advice.

---更新---

正如@kriegaex 所指出的,为了更好的可读性和可维护性,切入点表达式可以重写为

execution(* com.package..*.save*())

execution(* save*()) && within(com.package..*)