admin管理员组

文章数量:1565812

在运行spring测试程序时出现了

org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'accountService' is expected to be of type 'service.impl.AccountServiceImpl' but was actually of type 'jdk.proxy2.$Proxy24'

异常。

测试程序如下:

ApplicationContext app=new AnnotationConfigApplicationContext(Spring6Config.class);
        AccountServiceImpl accountService = app.getBean("accountService", AccountServiceImpl.class);


异常发生的背景:类AccountServiceImpl继承了接口AccountService,现在需要代理类AccountServiceImpl,出现了如标题所示格式的异常。


异常发生原因:JDK动态代理只能代理接口,若要代理类,需要使用cglib或其他代理方式。


异常的解决方法:

1.修改测试程序代码,将返回值改为类继承的接口:

ApplicationContext app=new AnnotationConfigApplicationContext(Spring6Config.class);
        AccountService accountService = app.getBean("accountService", AccountService.class);

2.修改spring的XML配置文件:

(1).使用aop配置:
    <aop:config proxy-target-class="true"> </aop:config>

(2). aspectj配置:
    <aop:aspectj-autoproxy proxy-target-class="true"/>

(3). 事务annotation配置:
    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>

3种配置,只要使用一种即可,设置proxy-target-class为true即使用cglib的方式代理对象。

总结了基本算是四种方法。

本文标签: xxxexpectedbeannamedtype