Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法使用相对路径导入SpringBean定义文件_Java_Spring_Unit Testing - Fatal编程技术网

Java 无法使用相对路径导入SpringBean定义文件

Java 无法使用相对路径导入SpringBean定义文件,java,spring,unit-testing,Java,Spring,Unit Testing,我是Spring新手,继承了一个Spring项目,该项目在ProjectName/WebContent/WEB-INF/applicationContext.XML中具有所有XML配置。我试图将配置分解为不同的组件,以便在测试时更容易替换数据源和Hibernate配置等内容 以下是我的文件结构: ProjectName ->WebContent ->WEB-INF ->applicationContext.xml ->

我是Spring新手,继承了一个Spring项目,该项目在ProjectName/WebContent/WEB-INF/applicationContext.XML中具有所有XML配置。我试图将配置分解为不同的组件,以便在测试时更容易替换数据源和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 -->
<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 -->
现在,如果我将spring-persistence.xml移动到/test中,这样我就不必使用相对路径,并用
引用它,那么测试运行良好。因此,我认为XML文件的内容是可以的,但我没有使用相对路径正确导入

在导入相对路径时是否有明显的错误?也许更大的问题是,这看起来是否是一种合理的策略,可以将applicationContext.xml分解为组件,以使其更易于测试


谢谢

问题是:在常规项目设置中,类加载器无法使用WEB-INF中的任何内容(spring默认使用类加载器访问资源)。有一些方法可以解决这个问题(比如使用file:prefix引用上下文),但这些方法大多很难看

我建议的一个更好的做法是将上下文文件从WEB-INF中移出,并移到一个专用的资源目录中(如果您有maven设置,则为src/main/resources)。这样,webapp类加载器和本地单元测试类加载器都可以使用它们

阅读以进一步了解所涉及的机制。

使用

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


它在spring 3.2.1.1版本中工作。旧版本我不确定。

谢谢肖恩的解释。我们使用的是Ant,只有src、test和WebContent/WEB-INF作为项目根节点的3个节点。将生产SpringXML文件放在src目录中,将测试SpringXML放在测试目录中是一种典型的设置吗?或者是非Maven设置中常用的其他位置。谢谢@是的,可以。在maven中,有一个将类与资源分开的约定,但是对于类加载器来说是一样的。如果是这样的话,我的jar(带bean)怎么可能放在/applications/Foo.ear/FooWebApp.war/WEB-INF/lib中,并且一切都正常呢@voipp如果是这样的话?
 <import resource="file:**/WebContent/WEB-INF/spring-persistence.xml" />