Spring aop报错:com.sun.proxy.$Proxy cannot be cast to xxx

1 篇文章 0 订阅
1 篇文章 0 订阅

描述错误


  1. 有一个 BaseService 接口
    public interface BaseService<T>
    2.有一个BaseServiceImpl 实现类
    public class BaseServiceImpl implements BaseService
    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 就对了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值