【发布时间】:2015-10-15 17:44:03
【问题描述】:
我正在尝试在当前的 spring 应用程序中实现某种条件导入 bean 上下文文件。为了完成这项工作,我在 SO 中使用类似的解决方案来扩展 ApplicationContextInitializer<ConfigurableApplicationContext>
package com.mydepartment.app.util;
public class MyApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
ConfigurableEnvironment env = applicationContext.getEnvironment();
// load from web.xml context-param
String propertyFileClassPath = env.getProperty("propertyFileClassPath");
try {
MutablePropertySources sources = env.getPropertySources();
sources.addFirst(new ResourcePropertySource(new ClassPathResource(propertyFileClassPath)));
} catch (IOException ioException) {
LOG.info(ioException.getMessage());
LOG.error( "Loading resource failed..", ioException);
}
}
}
这是希望我添加到 web.xml 以使当前应用程序能够加载包含定义条件的属性的属性文件
<context-param>
<param-name>contextInitializerClasses</param-name>
<param-value>com.mydepartment.app.util.MyApplicationContextInitializer</param-value>
</context-param>
<context-param>
<param-name>propertyFileClassPath</param-name>
<param-value>classpath*:application-env.properties</param-value>
</context-param>
.....
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
application-env.properties 驻留在
%war_file_name%\WEB-INF\classes\application-env.properties
但上面的配置/编码在 WebLogic 和 Websphere 中都返回以下错误,这让我对修复感到非常痛苦:
2015-10-15 13:23:12,625 -- INFO -- com.mydepartment.app.util.MyApplicationContextInitializer -- class path resource [classpath*:application-env.properties] cannot be opened because it does not exist
2015-10-15 13:23:12,626 -- ERROR -- com.mydepartment.app.util.MyApplicationContextInitializer -- Loading resource failed..
java.io.FileNotFoundException: 类路径资源 [classpath*:application-env.properties] 无法打开,因为它不存在
我尝试了几种模式来建立类路径,但都失败了,例如:
classpath*:application-env.properties
file:/WEB-INF/classes/application-env.properties
/WEB-INF/classes/application-env.properties
../classes/application-env.properties
可能我希望应用程序从应用程序内的属性文件加载初始化属性,而不是系统属性或服务器属性。但我认为没有必要将属性文件添加到服务器的类路径中。
我看不出应用服务器阻止访问此内部属性文件的任何原因。
【问题讨论】:
-
使用
classpath:而不是classpath*:。 -
@M. Deinum 谢谢,但它仍然失败:“加载到上下文时无法加载
classpath:/application-env.properties,加载顺序为 'FIRST'” -
@M.Deinum Deinum 还有
alsoclass 路径资源[classpath:/application-env.properties] 无法打开,因为它不存在`` -
文件真的在那个位置吗?
标签: java spring jakarta-ee websphere weblogic