我是Spring的新手,並且繼承了ProjectName/WebContent/WEB-INF/applicationContext.xml中的所有XML配置的Spring項目。我試圖將配置分解成不同的組件,以便在測試時更容易替換DataSources和Hibernate配置等。無法使用相對路徑導入Spring bean定義文件
這裏是我的文件結構:
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測試引用彈簧試驗豆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 -->
這樣,我可以指定數據源的測試和休眠特性,但重用生產映射文件的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
現在,如果我動彈簧的persistence.xml到/試驗,這樣我就不必使用相對路徑,並與<import resource="spring-persistence.xml"/>
引用它,則測試運行良好。所以我認爲我的XML文件的內容是確定的,但我沒有正確導入相對路徑。
有沒有什麼明顯的我做錯了我的導入相對路徑?也許更大的問題是,這看起來像是將applicationContext.xml分解爲組件以使其更易於測試的合理策略?
謝謝!
謝謝你的解釋肖恩。我們使用Ant,並且只有src,test和WebContent/WEB-INF作爲項目根目錄中的3個節點。將生產Spring xml文件放在src目錄中,並且測試目錄中的Spring xml是典型的安裝程序?或者在非Maven設置中常用的其他位置。謝謝! – buck64 2011-12-22 21:21:53
@ buck64是的,這樣做。在maven中有一個保持班級與資源分離的約定,但對於類加載器來說,它是完全一樣的。 – 2011-12-23 10:20:09
如果它的情況下,我的罐子(有豆子)放在/applications/Foo.ear/FooWebApp中怎麼可能。war/WEB-INF/lib和一切正常!? – voipp 2015-09-01 08:22:27