开发Spring过程中几个常见异常(三):java.lang.ClassCastException: com.sun.proxy.$Proxy4 cannot be cast to com.edu.a...

这个异常是在开发Spring案例时遇到的。

贴一下完整异常信息:

Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy4 cannot be cast to com.edu.aop.ArithmeticCalculatorImpl
    at com.edu.aop.Main.main(Main.java:11)

原因:Spring AOP是实现AOP的一种技术,是采用“动态代理技术”实现的。

在该案例中用到了接口,其中小编定义了一个接口ArithmeticCalculator,然后用实体类ArithmeticCalculatorImpl实现了这个接口。

错误代码定位在(此处贴出代码第二句):

ApplicationContext act=new ClassPathXmlApplicationContext("applicationContext.xml");
ArithmeticCalculatorImpl arithmetic=(ArithmeticCalculatorImpl)act.getBean("arithmetic");

再贴一下配置文件中配置信息:

<!-- 配置bean -->
<bean id="arithmetic" class="com.edu.aop.ArithmeticCalculatorImpl"></bean>

可以看到配置的bean是接口的实现类,那么String AOP技术对其进行动态代理,代理的结果对象和这个接口的实现类是同级的。也就是说代理对象和小编定义的接口实现类分别实现了该接口,二者之间根据java语言的转换原则是不能转换的,因此抛出转换异常。

当把转换类型换成接口类型时,就可解决这个异常了。即将红色代码部分改成:

ArithmeticCalculator arithmetic=(ArithmeticCalculator)act.getBean("arithmetic");

参考博客:

http://blog.csdn.net/yinzn2011/article/details/46455973

http://blog.csdn.net/a1491918446/article/details/48715247

 

转载于:https://www.cnblogs.com/dudududu/p/8487451.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值