在Spring AOP中使用@AfterReturning修改类中的值 [英] Modify value from class with @AfterReturning in Spring AOP

查看:643
本文介绍了在Spring AOP中使用@AfterReturning修改类中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to modify value with @AfterReturning advice, it works for any object except String. I know that String is Immutability. and how to modify the string without changing returning type of saveEverything() function in AccountDAO class? here are code snippet:

@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();
  }
}

推荐答案

来自文档:

请注意,不可能返回完全不同的返回建议后使用时的参考.

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

anavaras lamurep 在注释中正确指出, @Around 建议可用于满足您的要求.一个示例方面如下

As anavaras lamurep rightly pointed out in the comments , @Around advice can be used to achieve your requirement. An example aspect would be as follows

@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;
    }
}

请注意,问题中给出的切入点表达式是global.该表达式将匹配从 save 开始并返回 Object 的任何spring bean方法的调用.这可能会产生不希望的结果.建议将类的范围限制为建议.

Please note that the pointcut expression given in the question is global . This expression will match call to any spring bean method starting with save and returning an Object. This might have undesired outcome. It is recommended to limit the scope of classes to advice.

---更新---

如@kriegaex所指出的那样,为了提高可读性和可维护性,可以将切入点表达式改写为任意一个

As pointed out by @kriegaex , for better readability and maintainability the pointcut expression may be rewritten as either

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

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

这篇关于在Spring AOP中使用@AfterReturning修改类中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆