如何使用@AfterReturning建议修改值,它适用于String以外的任何对象。我知道String是不可变的。以及如何在不更改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();
}
}
请注意,不可能返回完全不同的返回建议后使用时的参考。
正如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;
}
}
[请注意,问题中给出的切入点表达式是global。该表达式将使调用与从save
开始并返回Object
的任何spring bean方法匹配。这可能会产生不良结果。建议将类的范围限制为建议。