刚刚写一个项目的时候出现了一个错误 com.sun.proxy.$Proxy25 cannot be cast to com.levi.service.impl.ProductServiceImpl,之前报错的代码为:
ProductServiceImpl p=(ProductServiceImpl) applicationContext.getBean("productService");
上面的ProductServiceImpl类是一个实现的ProductService接口的。利用spring ioc获取这个productService
bean的时候,不能转换为
ProductServiceImpl,而只能转为它的父接口ProductService。查了很多资料,发现是Spring AOP的一个配置文件问题。proxy-target-class这个参数。将spring配置文件改为下面就行了:
<!-- 配置事务切面 -->
<aop:config proxy-target-class="true">
<aop:pointcut id="serviceOperation"
expression="execution(* com.levi.service..*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation" />
</aop:config>
<!-- 自动扫描加载构建bean -->
<context:component-scan base-package="com.levi" />
proxy-target-class属性值决定是基于接口的还是基于类的代理被创建。如果proxy-target-class 属性值被设置为true,那么基于类的代理将起作用(这时需要cglib库)。如果proxy-target-class属值被设置为false或者这个属性被省略,那么标准的JDK 基于接口的代理将起作用。