开发Spring过程中几个常见异常(三):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案例时遇到的。

贴一下完整异常信息:

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

 

posted @ 2018-03-01 11:07  小杜同学的嘚啵嘚  阅读(718)  评论(0编辑  收藏  举报