junit測試,使用classpath和file 加載文件的區別


用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加載配置文件。

例如:

  1. @RunWith(SpringJUnit4ClassRunner.class)  
  2. @ContextConfiguration(locations={"classpath:spring-dao-test.xml"}) 

  public void TestA{

     }

然后發現一直不能將dao接口注入到impl實現類中,其實本質原因還是配置文件沒有加載對。

一直在糾結中..............

然后又用

  1. @RunWith(SpringJUnit4ClassRunner.class)  
  2. @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:com/myapp/config.xml

從classpath中加載。

file:

file:/data/config.xml

作為 URL 從文件系統中加載。

http:

http://myserver/logo.png

作為 URL 加載。

(none)

/data/config.xml

根據 ApplicationContext 進行判斷。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM