用junit測試發現一個問題,怎么加載配置文件?一直都出現這樣的錯誤
ERROR: org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@2d2bf892] to prepare test instance [com.zdwl.test.WriteData@21cc5069]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.zdwl.test.WriteData': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.zdwl.dao.impl.JdbcDaoImpl com.zdwl.test.WriteData.jdbcDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.zdwl.dao.impl.JdbcDaoImpl] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}\
以前都是用classpath加載配置文件。
例如:
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(locations={"classpath:spring-dao-test.xml"})
public void TestA{
}
然后發現一直不能將dao接口注入到impl實現類中,其實本質原因還是配置文件沒有加載對。
一直在糾結中..............
然后又用
- @RunWith(SpringJUnit4ClassRunner.class)
- @ContextConfiguration(locations={"file:WEB-INFO/spring-dao-test.xml"})
還是不對。
又用classpath*:/spring-dao-test.xml 加載 。。。。還也不能加載。。。我也暈了,咋整都不行呢?
然后又在其他項目里發現測試用的是:file:/spring-dao-test.xml;我就思考為什么用file加載,而不是classpath去加載配置文件。
最終。。。。
file:加載非編譯類的文件系統,即:作為 URL 從文件系統中加載。
classpath:加載編譯的class文件系統,即:從classpath中加載。
由於我的配置文件是非編譯類配置文件。所以我選擇用file:加載配置文件。寫全配置文件的絕對路徑。
以下是加載配置文件的classpath,file的表格對比:
| 前綴 | 例子 | 說明 |
|---|---|---|
| classpath: |
|
從classpath中加載。 |
| file: |
|
|
| http: |
|
作為 |
| (none) |
|
根據 |
