如何使用@AfterReturning建议修改值,它适用于除字符串之外的任何对象。我知道字符串是不可变的。以及如何在不更改 AccountDAO 类中 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();
}
}
从文档中:返回建议后
请注意,不可能退回完全不同的
退货后使用时参考。
As 阿纳瓦拉斯·拉穆雷普评论中正确指出,@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;
}
}
请注意,问题中给出的切入点表达式是全局的。该表达式将匹配对以以下开头的任何 spring bean 方法的调用save
并返回一个Object
。这可能会产生不希望的结果。建议将课程范围限制为建议。
- - 更新 - -
正如 @kriegaex 所指出的,为了更好的可读性和可维护性,切入点表达式可以重写为
execution(* com.package..*.save*())
or
execution(* save*()) && within(com.package..*)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)