您的位置:首页 > 运维架构

继承PropertyPlaceholderConfigurer 实现动态加载配置文件

2017-03-25 18:27 621 查看
  在项目开发的过程中,往往有多个环境,dev,test,uat,run等.各个环境的配置文件是不同的.改造spring的PropertyPlaceholderConfigurer可以实现为各个不同的环境读取到各自的配置文件.这样为项目的部署省去很多工作.

  Spring 的配置文件中,PropertyPlaceholderConfigurer 是占位符配置.为PropertyPlaceholderConfigurer 配置 .properties文件后,在Spring的配置文件中就可以使用${}的方式获取.properties数据.

  假设现有dev,test,uat,run四个环境,在每个项目web容器启动参数里面添加不同启动参数,下图以dev为例



  创建动态加载配置文件的DynamicServerConfig.java文件,核心方法为loadProperties,如下

  

package com.iris.spring.config;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.Resource;
import org.springframework.util.DefaultPropertiesPersister;
import org.springframework.util.PropertiesPersister;

/**
*
* @author xiami
*
*/
public class DynamicServerConfig extends PropertyPlaceholderConfigurer {
/** Logger available to subclasses */
protected final Log logger = LogFactory.getLog(getClass());

protected Properties[] localProperties;

protected boolean localOverride = false;

private Resource[] locations;

private PropertiesPersister propertiesPersister = new DefaultPropertiesPersister();

/**
* copy
*/
public void setLocations(Resource[] locations) {
this.locations = locations;
}

/**
* copy
*/
public void setLocalOverride(boolean localOverride) {
this.localOverride = localOverride;
}

/**
* 根据启动参数,动态读取配置文件
*/
protected void loadProperties(Properties props) throws IOException {
if (locations != null) {
logger.info("Start loading properties file.....");
for (Resource location : this.locations) {
InputStream is = null;
try {
String filename = location.getFilename();
String env = "system." + System.getProperty("spring.profiles.active", "run") + ".properties";
if (filename.contains(env)) {
logger.info("Loading properties file from " + location);
is = location.getInputStream();
this.propertiesPersister.load(props, is);

}
} catch (IOException ex) {
logger.info("读取配置文件失败.....");
ex.printStackTrace();
throw ex;
} finally {
if (is != null) {
is.close();
}
}
}
}

}
}


  在Spring配置文件中applicationContext.xml中配置DynamicServerConfig.

<bean id="PropertyPlaceholderConfigurer" class="com.iris.spring.config.DynamicServerConfig">
<property name="locations">
<list>
<value>classpath:config/system.development.properties</value>
<value>classpath:config/system.run.properties</value>
<value>classpath:config/system.test.properties</value>
<value>classpath:config/system.uat.properties</value>
</list>
</property>
</bean>


这样在tomcat启动的时候,Spring就会读取system.development.properties文件中的信息,不会读取其他几个文件中的信息.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐