报错内容:Error creating bean with name 'account.aop.test.AccountService2Test': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'accountService2Proxy' is expected to be of type 'account.aop.service.AccountService2Impl' but was actually of type 'com.sun.proxy.$Proxy30'
Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'accountService2Proxy' is expected to be of type 'account.aop.service.AccountService2Impl' but was actually of type 'com.sun.proxy.$Proxy30'
xml代码如下:
<!-- 注入dao -->
<bean id="accountDao2" class="account.aop.dao.AccountDao2Impl">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 注入service -->
<bean id="accountService2" class="account.aop.service.AccountService2Impl">
<property name="accountDao2" ref="accountDao2"/>
</bean>
<!-- 通过context标签引入外部文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 配置是C30连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driverClassName}"/>
<property name="jdbcUrl" value="${url}"/>
<property name="user" value="${user}"/>
<property name="password" value="${pass}"/>
</bean>
<!-- 配置平台事务管理器============================= -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property ref="dataSource" name="dataSource"/>
</bean>
<!-- 编写代理类,通过aop的前置增强的方法实现事物转账 -->
<bean id="accountService2Proxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<!-- 注入事物管理器 -->
<property name="transactionManager" ref="transactionManager"/>
<!-- 配置目标对象 -->
<property name="target" ref="accountService2"/>
<!-- 注入事物属性 -->
<property name="transactionAttributes">
<props>
<prop key="transfer">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
测试类:package account.aop.test;
import javax.annotation.Resource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import account.aop.service.AccountService2Impl;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:dl.xml")
public class AccountService2Test {
//@Resource(name="accountService2")
@Resource(name="accountService2Proxy")
private AccountService2Impl accountService2;
@Test
public void test() {
accountService2.transfer("zuo", "you", 300);
}
}
可能是Spring使用代理机制导致的(只看到错误信息和xml文件,大概猜测的原因)
使用JDK动态代理不支持类注入,只支持接口方式注入
如果想类注入可以使用cglib代理
你xml配置文件中注入service使用的是实现类而不是接口:
<bean id="accountService2" class="account.aop.service.AccountService2Impl"> <property name="accountDao2" ref="accountDao2"/> </bean>
应该改为:
<bean id="accountService2" class="account.aop.service.AccountService2"> <property name="accountDao2" ref="accountDao2"/> </bean>
注入dao部分应该也要类似修改。