[英]UnexpectedRollbackException in Spring with AOP @AfterReturning
[英]Modify value from class with @AfterReturning in Spring AOP
如何使用@AfterReturning 建議修改值,它適用於除字符串之外的任何 object。 我知道字符串是不變性的。 以及如何在不更改 AccountDAO class 中的 saveEverything() function 的返回類型的情況下修改字符串? 這是代碼片段:
@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();
}
}
來自文檔: 返回通知后
請注意,在返回通知后使用時,不可能返回完全不同的參考。
正如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;
}
}
請注意,問題中給出的切入點表達式是全局的。 此表達式將匹配對任何 spring bean 方法的調用,該方法以save
開頭並返回Object
。 這可能會產生不希望的結果。 建議將 scope 類限制為建議。
- - 更新 - -
正如@kriegaex 所指出的,為了更好的可讀性和可維護性,切入點表達式可以重寫為
execution(* com.package..*.save*())
或者
execution(* save*()) && within(com.package..*)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.