代码之家  ›  专栏  ›  技术社区  ›  hammerfest

由于属性文件位置类型,应用程序或集成测试Spring上下文创建失败

  •  0
  • hammerfest  · 技术社区  · 7 年前

    .properties 在主机文件系统上部署时创建的文件,因此它不会与应用程序捆绑在一起 .war 在构建时。它在Spring应用程序上下文创建期间由加载程序类打开和读取

    <bean id="propertiesLoader" class="com....PropertiesLoader">
      <property name="propertiesFileLocation" value="${PROPERTIES_FILE_LOCATION}"/>
      ...
    

    其中的文件路径值 PROPERTIES_FILE_LOCATION 定义在 application.properties 归档 src\main\resources 应用程序的 -web maven模块

    PROPERTIES_FILE_LOCATION=/home/.../propertyfilename.properties
    

    propertiesFileLocation 领域是 String new FileInputStream(propertiesFileLocation) 在里面 PropertiesLoader.java 班

    通过此设置,应用程序上下文创建成功。然而,我们的项目中也有一些集成测试,这些测试也为它们的执行设置了一个Spring上下文。我们想储存一份 propertyfilename.properties 归档 src\test\resources 的 -it maven模块,并从其 it.properties 喜欢

    PROPERTIES_FILE_LOCATION=classpath:somedirectory/propertyfilename.properties    
    

    但是,在创建集成测试上下文的过程中,我们收到以下异常

    [ERROR] Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean
    with name 'propertiesLoader' defined in URL 
    [ERROR] Caused by: java.io.FileNotFoundException: classpath:somedirectory\propertyfilename.properties  
    (The filename, directory name, or volume label syntax is incorrect)
    

    现在,如果我们修改 属性文件位置 字段到 org.springframework.core.io.Resource 我们通过 propertiesFileLocation.getInputStream() PropertiesLoader.java ,这使得集成测试上下文创建成功,但同时实际应用程序上下文创建失败

    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'propertiesLoader' defined in URL 
    [file:/.../tomcat/work/Catalina/localhost/_/loader/conf/spring/springmvc/springmvc-util.xml]: Invocation of init method failed; 
    nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/home/.../propertyfilename.properties]
    

    这似乎是一种“死锁”情况,因为应用程序或集成测试上下文创建失败。是否有一种方法可以成功地创建这两个上下文?

    1 回复  |  直到 7 年前
        1
  •  1
  •   M. Deinum    7 年前

    资源加载在 Spring References Guide ApplicationContext . 对于将成为存档根目录的web应用程序,基本上 WEB-INF

    您想为该前缀加载一个文件资源,该前缀包含该资源 file: 在你的测试中使用 classpath: 从`类路径'加载它。这样,无论应用程序上下文使用哪个默认位置,它都可以工作。