您的位置:首页 > 编程语言 > Java开发

JAVA获取内部及外部配置

2016-04-29 11:05 459 查看
获取内部配置

PropertiesUtils.java

package cn.ting.common.util;

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

import org.apache.log4j.Logger;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

public class PropertiesUtils {

private static final Logger log = Logger.getLogger("PropertiesUtils");

private static PropertiesUtils propertiesUtils = null;
private Properties config = null;

public PropertiesUtils(){
try {
Resource resource = new ClassPathResource("/env.properties");
config = PropertiesLoaderUtils.loadProperties(resource);
} catch (IOException e) {
log.error(e.getMessage());
throw new RuntimeException("找不到配置文件:env.properties");
}
}

public static String getProperty(String key){
return getConfig().getProperty(key);
}

private static Properties getConfig(){
if(null == propertiesUtils){
propertiesUtils = new PropertiesUtils();
}
return propertiesUtils.config;
}
}


获取外部配置

ExternalPropertiesUtils.java

package cn.ting.common.util;

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

import org.apache.log4j.Logger;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

public class ExternalPropertiesUtils {

private static final Logger log = Logger.getLogger("ExternalPropertiesUtils");

private static ExternalPropertiesUtils externalPropertiesUtils = null;
private Properties config = null;

public ExternalPropertiesUtils(){
try {
String path = PropertiesUtils.getProperty("external.properties.path");
Resource resource = new FileSystemResource(path);
config = PropertiesLoaderUtils.loadProperties(resource);
} catch (IOException e) {
log.error(e.getMessage());
throw new RuntimeException("找不到外部配置文件");
}
}

public static String getProperty(String key){
return getConfig().getProperty(key);
}

private static Properties getConfig(){
if(null == externalPropertiesUtils){
externalPropertiesUtils = new ExternalPropertiesUtils();
}
return externalPropertiesUtils.config;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: