2014-02-16 74 views
1

我有一個Java接口:@Autowired總是得到空

public interface TestRequestDAO { 
    ... 
} 

而且接口的實現:

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

現在,我從另一個類自動裝配Bean的像下面並獲得null始終:

@Autowired 
private TestRequestDAO requestDao; 

這是我的春天上下文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結束。但似乎沒有什麼與我一起工作。我已經通過行家改變了這個版本:

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

回答

3

測試通常會是這個樣子:

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

然後還要組件注入進去,按要求。不要讓測試成爲一個組件。

如果該bean不是測試,請不要將其稱爲TestXyz。