簡體   English   中英

無法使用相對路徑導入Spring bean定義文件

[英]Unable to import Spring bean definition file using relative path

我是Spring的新手,並繼承了一個Spring項目,該項目在ProjectName / WebContent / WEB-INF / applicationContext.xml中具有所有XML配置。 我正在嘗試將配置分解為不同的組件,以便在測試時更容易替換DataSources和Hibernate配置等內容。

這是我的文件結構:

ProjectName
  ->WebContent
      ->WEB-INF
          ->applicationContext.xml
          ->spring-datasource.xml
          ->spring-hibernate-properties.xml
          ->spring-persistence.xml
  ->test
      ->us.mn.k12... (Java pkgs with JUnit tests)
      ->spring-hsqldb-datasource.xml
      ->spring-test-bean-locations.xml
      ->spring-test-hibernate-properties.xml
  ->src
      ->us.mn.k12... (Java pkgs with production code)

在WEB-INF / applicationContext.xml中,我導入以下內容:

<import resource="spring-datasource.xml"/> <!-- Production datasource -->
<import resource="spring-hibernate-properties.xml"/> <!-- Production hibernate properties -->
<import resource="spring-persistence.xml"/> <!--  DAO's, hibernate .hbm.xml mapping files -->

該應用程序使用上述配置。

我的JUnit測試使用DbUnit和HSQLDB內存數據庫運行。 所以我的JUnit測試引用了spring-test-bean-locations.xml,它具有以下內容:

<import resource="spring-hsqldb-datasource.xml"/> <!-- HSQLDB datasource for test -->
<import resource="../WebContent/WEB-INF/spring-persistence.xml"/>  <!--  Production DAO's, hibernate .hbm.xml mapping files -->
<import resource="spring-test-hibernate-properties.xml"/> <!-- Hibernate properties for test -->

通過這種方式,我可以指定測試數據源和hibernate屬性,但是重用DAO的生成映射文件等。但是,運行JUnit測試時出錯。 以下是例外的相關部分:

Caused by: org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: Failed to import bean definitions from relative location [../WebContent/WEB-INF/spring-persistence.xml]
Offending resource: class path resource [spring-test-bean-locations.xml]; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [../WebContent/WEB-INF/spring-persistence.xml]; nested exception is java.io.FileNotFoundException: class path resource [../WebContent/WEB-INF/spring-persistence.xml] cannot be opened because it does not exist

現在,如果我將spring-persistence.xml移動到/ test中,以便我不必使用相對路徑,並使用<import resource="spring-persistence.xml"/>引用它,那么測試運行正常。 所以我認為我的XML文件的內容是可以的,但我沒有正確導入相對路徑。

我輸入相對路徑有什么明顯的錯誤嗎? 也許更大的問題是,這看起來像是將applicationContext.xml分解為組件以使其更容易進行測試的合理策略嗎?

謝謝!

問題是:在常規項目設置中,ClassLoader中沒有WEB-INF內的任何內容(並且spring默認使用ClassLoader來訪問資源)。 有一些黑客可以解決這個問題(比如使用file:prefix引用上下文),但那些大多是丑陋的。

我建議的一個更好的做法是將上下文文件移出WEB-INF並進入專用資源目錄(如果你有maven設置,則為src / main / resources)。 這樣,它們將可用於webapp ClassLoader和本地單元測試ClassLoaders。

閱讀資源章節以進一步了解所涉及的機制。

使用

 <import resource="file:**/WebContent/WEB-INF/spring-persistence.xml" />

它適用於春季3.2.1.RELEASE。 舊版本我不確定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM