Java 由于属性文件位置类型,应用程序或集成测试Spring上下文创建失败
我们的应用程序应该使用在主机文件系统上部署时创建的Java 由于属性文件位置类型,应用程序或集成测试Spring上下文创建失败,java,spring,tomcat,properties,Java,Spring,Tomcat,Properties,我们的应用程序应该使用在主机文件系统上部署时创建的.properties文件,因此它不会在构建时与应用程序.war捆绑在一起。它在Spring应用程序上下文创建期间由加载程序类打开和读取 <bean id="propertiesLoader" class="com....PropertiesLoader"> <property name="propertiesFileLocation" value="${PROPERTIES_FILE_LOCATION}"/> .
.properties
文件,因此它不会在构建时与应用程序.war
捆绑在一起。它在Spring应用程序上下文创建期间由加载程序类打开和读取
<bean id="propertiesLoader" class="com....PropertiesLoader">
<property name="propertiesFileLocation" value="${PROPERTIES_FILE_LOCATION}"/>
...
propertiesFileLocation
字段的类型是String
,可以通过propertiesFileLocation.java
类中的newfileinputstream(propertiesFileLocation)
进行访问
通过此设置,应用程序上下文创建成功。然而,我们的项目中也有一些集成测试,这些测试也为它们的执行设置了一个Spring上下文。我们希望将propertyfilename.properties
文件的副本存储到-it
maven模块的src\test\resources
中,并从其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)
现在,如果我们将propertiesFileLocation
字段的类型修改为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]
这似乎是一种“死锁”情况,因为应用程序或集成测试上下文创建失败。是否有一种方法可以成功地创建这两个上下文?中的资源加载非常好。如果不在资源前面加上要从中加载资源的位置,它将默认为
ApplicationContext
的默认位置。对于将成为存档根目录的web应用程序,基本上是web-INF
目录中的内容\
您想为这个前缀加载一个文件资源,该资源带有
文件:
,并且在测试中使用类路径:
从“类路径”加载它。这样,无论应用程序上下文使用哪个默认位置,它都会工作。前缀在application.properties
中使用文件:
,而不是不使用前缀。@M.Deinum:谢谢,这似乎解决了问题。你愿意详细解释一下,让我接受吗?
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]