当使用tx:annotation-driven时,Spring 2.5 SpringJUnit4ClassRunner无法自动装配

时间:2012-05-16 02:23:42

标签: spring autowired

TestCode

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:transactional/batch/context.xml" })
public class TransactionTest {
@Autowired
TestBatch testBatch;

案例1: TestBatch成功自动连接到TransactionTest

context.xml中

<context:annotation-config />
<bean id="testBatch" class="transactional.batch.TestBatch"/>
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>

案例2: 但是这个案子失败了。

context.xml中

<context:annotation-config />
<bean id="testBatch" class="transactional.batch.TestBatch"/>
<tx:annotation-driven transaction-manager="transactionManager"/>

例外

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: transactional.batch.TestBatch transactional.batch.TransactionTest.testBatch; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [transactional.batch.TestBatch] is defined: Unsatisfied dependency of type [class transactional.batch.TestBatch]: expected at least 1 matching bean
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:435)
    at org.springframework.beans.factory.annotation.InjectionMetadata.injectFields(InjectionMetadata.java:105)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessAfterInstantiation(AutowiredAnnotationBeanPostProcessor.java:240)
    ... 19 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type [transactional.batch.TestBatch] is defined: Unsatisfied dependency of type [class transactional.batch.TestBatch]: expected at least 1 matching bean
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:613)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:412)
    ... 21 more

唯一的区别是tx:annotation-driven的{​​{1}}属性。

为什么proxy-target-class控制自动线?

1 个答案:

答案 0 :(得分:0)

我的猜测是TestBatch实现了一个接口,并且在某些方法上有@Transactional

<tx:annotation-driven>将为TestBatch生成一个事务代理对象。默认情况下,如果TestBatch实现任何接口,则此代理对象将实现这些接口,但不会扩展TestBatch. If you use proxyTargetClass , then the generated proxy object will instead subclass TestBatch`。

由于您的单元测试要求对象属于TestBatch类型,这意味着您必须在配置中使用proxyTargetClass。或者,更改单元测试,以便使用TestBatch的其中一个接口,而不是直接使用TestBatch类型。