首页 > 编程语言 > 详细

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

时间:2015-03-30 21:11:51      阅读:223      评论:0      收藏: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");

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

原文:http://blog.csdn.net/kuaisuzhuceh/article/details/44756333

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!