今天在学习Spring AOP的通知时发现无法获取切入方法返回值,控制台一直输出为null
具体的代码如下:
@Service//目标对象
public class MyServiceImpl implements MyService {
//连接点
public String b(){
System.out.println("被切方法");//3
return "b方法";
}
}
@Controller
public class DemoController {
@Autowired
private MyServiceImpl myService;
@ResponseBody
@RequestMapping("/a")
public String a(){
String b = myService.b();
System.out.println(b);
return "a方法执行";
}
}
@Pointcut("execution(java.lang.String com.example.aopdemo.service.impl.MyServiceImpl.b())")
public void pointcut1(){}//@PointCut实际上没什么作用,只是用来定义一个切点
@Around("pointcut1()")
public void around(ProceedingJoinPoint JoinPoint) throws Throwable {
System.out.println("环绕通知开始");//Object a =
JoinPoint.proceed();//将@Around通知的返回值定义为objec1t类型,
// 这样在proceed方法执行结束后就可以用Object来接收其返回值最后通过return将结果返回,否则环绕通知的返回值将会覆盖原来方法的返回值
System.out.println("环绕通知结束");//6
//return a;
}
可以看到在MyServiceImpl类中的b()方法是有返回值的,但是在控制台打印出来却是null
查阅资料后发现@Around的返回值类型必须是Object,而我返回的是void,会不会是这个问题呢
将代码修改为
@Around("pointcut1()")
public Object around(ProceedingJoinPoint JoinPoint) throws Throwable {
System.out.println("环绕通知开始");//Object a =
JoinPoint.proceed();//将@Around通知的返回值定义为objec1t类型,
// 这样在proceed方法执行结束后就可以用Object来接收其返回值最后通过return将结果返回,否则环绕通知的返回值将会覆盖原来方法的返回值
System.out.println("环绕通知结束");//6
return "环绕通知返回值";
}
运行程序,访问http://localhost:8080/a
运行结果如下
仍旧不是我们想要的值(b方法),而是around()方法的返回值,这说明之前打印的null值可能被around()返回的值覆盖了,或者说可能是around()方法返回值后被转换为String类型作为b()方法的返回值了,再次修改代码如下,使用一个Object a指向proceed()方法的返回值,并将这个引用作为返回值。
@Around("pointcut1()")
public Object around(ProceedingJoinPoint JoinPoint) throws Throwable {
System.out.println("环绕通知开始");//
Object a = JoinPoint.proceed();//将@Around通知的返回值定义为objec1t类型,
// 这样在proceed方法执行结束后就可以用Object来接收其返回值最后通过return将结果返回,否则环绕通知的返回值将会覆盖原来方法的返回值
System.out.println("环绕通知结束");//6
return a;
}
再次访问http://localhost:8080/a,结果如下
结果达到我们预期的目的。具体原理暂未深究。如有知道的小伙伴可以写在评论区。
才疏学浅,如有纰漏,希望各位多多包涵。



