在开发应用时,可能需要根据不同的环境使用不同的代码,部署时手动切换代码,比较麻烦,如果根据环境配置,自动切换代码,下面为一个示例
首先建立配置文件:
config.properties
class="java">#configure the environment
#dev,test,exp
env=dev
获取配置工具:
package com.test.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import common.Logger;
/**
* 环境配置工具类
* @author donald
* @date 2017-5-19
* @time 上午11:13:27
*/
public class ConfigUtil {
private static final Logger log = Logger.getLogger(ConfigUtil.class);
private static final String ENV = "env";
private static final String ENV_DEV = "dev";//开发环境
private static final String ENV_TEST = "test";//测试环境
private static final String ENV_EXP = "exp";//正式体验环境
private static final String CONFIG_FILE = "config.properties";
private static volatile ConfigUtil instance = null;
private static Properties envProperties = null;
static {
init();
}
public static synchronized ConfigUtil getInstance(){
if(instance == null){
instance = new ConfigUtil();
}
return instance;
}
/**
* 初始化配置文件
*/
private static void init(){
// String path = Thread.currentThread().getContextClassLoader().getResource(CONFIG_FILE).getPath();
// log.debug("==========congfig file path:"+path);
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(CONFIG_FILE);
envProperties = new Properties();
try {
envProperties.load(inputStream);
} catch (IOException e) {
log.error("====load config file error:"+e.getMessage());
e.printStackTrace();
}
}
/**
* 判断是否为开发环境
* @return
*/
public boolean getEnvDev(){
boolean flag = false;
String envConfig = getEnvConfig();
if(envConfig.equals(ENV_DEV)){
flag = true;
}
return flag;
}
/**
* 判断是否为测试环境
* @return
*/
public boolean getEnvTest(){
boolean flag = false;
String envConfig = getEnvConfig();
if(envConfig.equals(ENV_TEST)){
flag = true;
}
return flag;
}
/**
* 判断是否为正式环境
* @return
*/
public boolean getEnvExp(){
boolean flag = false;
String envConfig = getEnvConfig();
if(envConfig.equals(ENV_EXP)){
flag = true;
}
return flag;
}
/**
* 获取环境配置
* @return
*/
protected String getEnvConfig(){
String envConfig = envProperties.getProperty(ENV);
if(StringUtils.isBlank(envConfig)){
envConfig = ENV_DEV;
}
return envConfig;
}
/**
* 获取环境配置文件属性
* @return
*/
private Properties getEnvProperties(){
return envProperties;
}
public static void main(String[] args) {
{
if(ConfigUtil.getInstance().getEnvDev()){
log.info("==========congfig env:dev");
}
if(ConfigUtil.getInstance().getEnvTest()){
log.info("==========congfig env:test");
}
if(ConfigUtil.getInstance().getEnvExp()){
log.info("==========congfig env:exp");
}
}
}
}
最后用工具类获取环境配置,切换代码。