异步方法@Async报错的问题: Null return value from advice

在使用Spring的@Async注解进行异步方法调用时,遇到一个异常,当方法有原始类型(int)返回值时,会抛出AopInvocationException。原因是异步方法返回null与原始类型不匹配。解决方案包括将返回值类型改为void或者使用包装类(Integer),或者避免使用异步注解。理解这个机制有助于避免此类错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下午遇到一个奇怪的问题
总结就一下就是
使用@Async 异步执行的方法,如果有返回值,返回值不要用原始数据类型(比如int),最好使用包装类(比如Integer)
因为使用原始类型的话,会报错

org.springframework.aop.AopInvocationException: Null return value from advice does not match primitive return type for: public abstract int cn.xxx.xxx.entry.service.IEntryServiceLogSrv.updateByRequestIdSelective(cn.xxx.xxx.entry.model.vo.http.QueryEntryInfoResponse)
	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:227) ~[spring-aop-4.3.19.RELEASE.jar:4.3.19.RELEASE]
	at com.sun.proxy.$Proxy128.updateByRequestIdSelective(Unknown Source) ~[?:?]

在动态代理的源码中发现:

// file: JdkDynamicAopProxy.class  -- spring-aop-4.3.19.RELEASE.jar
                Class<?> returnType = method.getReturnType();
                if (retVal != null && retVal == target && returnType != Object.class && returnType.isInstance(proxy) && !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
                    retVal = proxy;
                } else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
                    throw new AopInvocationException("Null return value from advice does not match primitive return type for: " + method);
                }

解决办法

  1. 改为无返回值 void
  2. 改为使用包装类
  3. 不使用异步注解
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值