@Autowired总是变空

时间:2014-02-16 09:48:54

标签: spring

我有一个Java界面:

public interface TestRequestDAO {
    ...
}

接口的实现:

@Component
@ContextConfiguration(locations = "file:src/main/resources/my-context.xml")
public class TestRequestDAOImpl implements TestRequestDAO {
    ...
}

现在,我正在从另一个类(如下所示)自动装配Bean,并始终获得null

@Autowired
private TestRequestDAO requestDao;

这是我的spring上下文xml,名为my-context.xml,位于src/main/resources/目录中。

<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/context/spring-context-4.0.xsd" >

    <context:annotation-config/>
    <context:component-scan base-package="org.test.code"/>
</beans>

此示例基于其他stackoverflow问题。我添加了注释@ContextConfiguration,因为没有任何关系。

我正在使用Maven,我从春季版本2.5.5开始,以4.0.1.RELEASE结束。但似乎没有什么能和我合作。我已经通过maven改变了这个版本:

...
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <!--version>2.5.5</version-->
    <version>4.0.1.RELEASE</version>
</dependency>
...

1 个答案:

答案 0 :(得分:3)

测试通常看起来像这样:

@RunWith (SpringJUnit4ClassRunner.class)
@ContextConfiguration (locations = "classpath:applicationContext-test.xml")
@WebAppConfiguration
@Transactional
public MyTest {...}

然后根据需要将组件注入其中。不要将测试作为组件。

如果bean不是测试,请不要将其称为TestXyz。