java.lang.ClassCastException: com.sun.proxy.$Proxy* cannot be cast to***问题解决方案

1 篇文章 0 订阅

临床表现:

  1. 使用Spring AOP动态代理;
  2. 使用Spring管理的bean类继承自某个接口;
  3. Spring容器中有你要代理的bean的id,但是该id不能强制转换成Bean类。

病例:
定义代理类:

@Transactional
@Repository
public UserDaoImpl implements UserDao extends BaseDaoImpl{
/*没有实现任何接口*/
}

获取代理类:

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDaoImpl userDaoImpl = (UserDaoImpl)ctx.getBean("userDaoImpl");

报错:

java.lang.ClassCastException: com.sun.proxy.$Proxy12 cannot be cast to UserDaoImpl

病因:
对于Spring AOP 采用两种代理方法,一种是常规JDK,一种是CGLIB,我的UserDao了一个接口IUserDao,当代理对象实现了至少一个接口时,默认使用JDK动态创建代理对象,当代理对象没有实现任何接口时,就会使用CGLIB方法。点此查看详细介绍>>>
治疗方法
如果你的代理对象没有实现接口的方法,就将代理对象转换成接口。
获取代理类的代码该为:

ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDaoImpl)ctx.getBean("userDaoImpl");

  • 12
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值