org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'accounts' must be of t
描述:
在使用Spring AOP 时,启动服务抛出异常:
org.springframework.beans.factory.BeanNotOfRequiredTypeException
解决方案:
该问题往往因代码中默认使用了JDK的动态代理注入而引起的,由于JDK的动态代理不支持类注入,只支持接口注入。
解决方法有3种:
1、 修改代码,统一使用接口注入,不使用类注入;
2、 使用CGLib代理;
3、 在Spring的AOP配置中添加如下配置,使Spring代理目标类:
<aop:config proxy-target-class="true">
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/db_bank"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!-- 获得工厂-->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="typeAliasesPackage" value="com.bjsxt.pojo"></property>
</bean>
<!-- 扫描mapper映射文件-->
<bean id="mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="factory"></property>
<property name="basePackage" value="com.bjsxt.mapper"></property>
</bean>
<bean id="accounts" class="com.bjsxt.service.imple.AccountServiceImple">
<property name="accountMapper" ref="accountMapper"></property>
</bean>
<!-- -->
<aop:config proxy-target-class="true"></aop:config>
<!-- 创建事务对象-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 创建事务通知-->
<tx:advice id="ad" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="transfer"/>
</tx:attributes>
</tx:advice>
<!-- 配置事务切面-->
<aop:config>
<aop:pointcut id="txt" expression="execution(* com.bjsxt.service.imple.*.*(..))"/>
<aop:advisor advice-ref="ad" pointcut-ref="txt"></aop:advisor>
</aop:config>
</beans>
还没有评论,来说两句吧...