spring @afterreturning返回值
@afterreturning是用于做aop的,其中返回值的问题,坑了我比较久,特地写出来。
1. 正确的使用
@afterreturning(value = "pointcut()", returning = "obj") public object doafterreturning(joinpoint joinpoint, object obj) { // 正常情况下,我们想要修改obj,只需要强转为对应的对象,再重新设置值即可,如下 user user = (user)obj; user.setname("test"); return user; }
2. 错误的使用
@afterreturning(value = "pointcut()", returning = "obj") public object doafterreturning(joinpoint joinpoint, object obj) { // 直接修改了obj的引用地址 user user = new user(); obj = user; return obj; }
区别就是方式一并没有更改obj的引用指针地址,返回结果是更新了name属性后的用户
而方式二更改了obj引用指针,返回结果并不是新new的user对象,而是入参obj对象
所以使用时要注意:
afterreturning方法虽然能修改返回值,但是局限于相同的对象地址,即最后返回对象的引用地址和入参的引用地址必须相同。
所以能修改返回值的也只有引用类型,基本类型是不允许的
@afterreturning方法执行了,但是切入方法没执行
首先,在一个批量插入的方法定义了切入点
@pointcut(value = "execution(* com.cases.dao.mapper.duty.dutytabledao.insertbatch(..))") public void pointcut() { log.info("dutydeleteinterceptor:pointcut"); }
@afterreturning方法可以正常进入,但是批量插入insertbatch方法却没有执行。
原因就在@around注解方法
这是原来的代码
@around(value = "pointcut()") public void methodaround(proceedingjoinpoint joinpoint) throws throwable { log.info("dutydeleteinterceptor:methodaround"); }
修改后的代码
@around(value = "pointcut()") public object methodaround(proceedingjoinpoint joinpoint) throws throwable { log.info("dutydeleteinterceptor:methodaround"); return joinpoint.proceed(); }
调试,成功。
小知识:
joinpoint.proceed() 的返回值是object类型,object result = joinpoint.proceed();
其实这句代码的意思就是正常去执行我们的业务,返回值result,在错误代码中,返回值写成了void,所以正常业务拿不到返回值了
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论