描述错误
-
有一个 BaseService 接口
public interface BaseService<T>
public class BaseServiceImpl implements BaseService
2.有一个BaseServiceImpl 实现类
3.
有一个类继承了BaseServiceImpl 并没有 实现一个接口
public class UserServiceImpl extends BaseServiceImpl
aop配置
<!-- aop配置 -->
<aop:config>
<aop:pointcut id="mypoint" expression="execution(* www.change.tm.shop.service.impl..*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="mypoint" />
</aop:config>
service配置:
<bean id="baseService" class="www.change.tm.shop.service.impl.BaseServiceImpl">
<property name="baseDao" ref="baseDao" />
</bean>
<bean id="userService" class="www.change.tm.shop.service.impl.UserServiceImpl" parent="baseService"/>```
当我写测试service的时候
private UserServiceImpl userServiceImpl;
private ApplicationContext applicationContext;
private AbstractApplicationContext ac;
@Before
public void beforA(){
applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
userServiceImpl = (UserServiceImpl) applicationContext.getBean("userService");
}
“`
测试的时候 会报错。显示 java.lang.ClassCastException: com.sun.proxy.$Proxy41 cannot be cast to www.change.tm.shop.service.impl.UserServiceImpl
这个原因 :
查了很久 http://www.bubuko.com/infodetail-1319893.html
这篇文章说
是因为aop配置中
这个proxy-target-class属性 :
proxy-target-class属性值决定是基于接口的还是基于类的代理被创建。如果proxy-target-class 属性值被设置为true,那么基于类的代理将起作用(这时需要cglib库)。如果proxy-target-class属值被设置为false或者这个属性被省略,那么标准的JDK 基于接口的代理
jdk基于接口的代理:
开始看JDK的Proxy代码。使用JDK动态代理的代码代码
ITestBean tb = (ITestBean) Proxy.newProxyInstance(tb.getClass().getClassLoader(), tb.getClass().getInterfaces(), new TestBeanHander(tb));
于是从创建代理函数看起,即public static Object newProxyInstance(ClassLoader loader,
Class
解决办法是
<!-- aop配置 -->
<aop:config proxy-target-class="true">
<aop:pointcut id="mypoint" expression="execution(* www.change.tm.shop.service.impl..*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="mypoint" />
</aop:config>
写上true 就对了