关于事物默认使用JDK动态代理导致的错误

//错误代码
   @Scheduled(cron = "0 0 2 * * ?")
   @Transactional(rollbackFor = Exception.class)
    public void sampleTaskManagement() {
    //.......
    }

问题描述:在定时任务上加了事物注解报错
Caused by: java.lang.IllegalStateException: Need to invoke method ‘sampleTaskManagement’ declared on target class ‘SampleTaskManagementSchedule’, but not found in any interface(s) of the exposed proxy type. Either pull the method up to an interface or switch to CGLIB proxies by enforcing proxy-target-class mode in your configuration.

这个错误提示说明在目标类(SampleTaskManagementSchedule)的代理类型中没有找到被代理的方法(sampleTaskManagement)的声明。这可能是因为你的配置使用了基于接口的代理(JDK动态代理),但目标类中没有相应的接口

事务的实现是通过AOP(面向切面编程)来实现的。当你在方法上添加@Transactional注解时,Spring就会创建一个动态代理来管理事务,如果没有显式地配置,Spring将默认使用JDK动态代理。而JDK动态代理要求被代理的类必须实现接口,因此会导致该问题。

将事物的代理方式改为cglib,或者创建该类的接口

@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
public class AppConfig {
    // 其他配置
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值