java.lang.ClassCastException: com.sun.proxy.$Proxy28 cannot be cast to com.dong.service.impl.AccountServiceImpl错误
今天在做项目时出现这么一个错误,在网上找了一些解决方案,最终是解决了。
我把错误的症状写出来,看看你们是否与我的相同。
错误现象:在没有配置下面这段配置时,二号代码并不会报错。
在配置之后,二号代码运行时就会报错。
<!--一号代码-->
<aop:config>
<aop:aspect ref="myAspect">
<aop:after method="after" pointcut="execution(public void com.dong.aop.TargetInterface.selectAll())"></aop:after>
<aop:after method="after" pointcut="execution(public void com.dong.service.AccountService.saveAccount(..))"></aop:after>
</aop:aspect>
</aop:config>
就下面这段代码,是AccountService接口的一个
<!--二号代码-->
AccountServiceImpl acc = app.getBean("accountServiceImpl",AccountServiceImpl.class);
acc.findAll();
原因:1.没有配置一号代码时,AOP没有配置,二号代码就会将getBean()的object对象强转为AccountServiceImpl对象。
2.在配置了一号代码时,AccountServiceImpl有一个接口,就会默认的使用jdk代理方式,而返回的代理对象是用接口类型AccountService接收的,由于不能向下转型就导致了错误。
解决方案:将AccountServiceImpl的bean对象用AccountService接口接收。
AccountService acc = app.getBean("accountServiceImpl",AccountService.class);
acc.findAll();