试试下面的。创建一个ApplicationContextInitializer
在 Web 上下文中:ApplicationContextInitializer<ConfigurableWebApplicationContext>
并通过以下方式在 web.xml 中注册它:
<context-param>
<param-name>contextInitializerClasses</param-name>
<param-value>...ContextInitializer</param-value>
</context-param>
在 ContextInitializer 中,您可以通过类路径和文件系统添加属性文件(虽然没有尝试过 JNDI)。
public void initialize(ConfigurableWebApplicationContext applicationContext) {
String activeProfileName = null;
String location = null;
try {
ConfigurableEnvironment environment = applicationContext.getEnvironment();
String appconfigDir = environment.getProperty(APPCONFIG);
if (appconfigDir == null ) {
logger.error("missing property: " + APPCONFIG);
appconfigDir = "/tmp";
}
String[] activeProfiles = environment.getActiveProfiles();
for ( int i = 0; i < activeProfiles.length; i++ ) {
activeProfileName = activeProfiles[i];
MutablePropertySources propertySources = environment.getPropertySources();
location = "file://" + appconfigDir + activeProfileName + ".properties";
addPropertySource(applicationContext, activeProfileName,
location, propertySources);
location = "classpath:/" + activeProfileName + ".properties";
addPropertySource(applicationContext, activeProfileName,
location, propertySources);
}
logger.debug("environment: '{}'", environment.getProperty("env"));
} catch (IOException e) {
logger.info("could not find properties file for active Spring profile '{}' (tried '{}')", activeProfileName, location);
e.printStackTrace();
}
}
private void addPropertySource(ConfigurableWebApplicationContext applicationContext, String activeProfileName,
String location, MutablePropertySources propertySources) throws IOException {
Resource resource = applicationContext.getResource(location);
if ( resource.exists() ) {
ResourcePropertySource propertySource = new ResourcePropertySource(location);
propertySources.addLast(propertySource);
} else {
logger.info("could not find properties file for active Spring profile '{}' (tried '{}')", activeProfileName, location);
}
}
上面的代码尝试为每个活动配置文件查找一个属性文件(请参阅:如何通过属性文件而不是通过 env 变量或系统属性设置活动 spring 3.1 环境配置文件)