JAVA獲取內部及外部配置

獲取內部配置java

PropertiesUtils.javaweb

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;
    }
}

獲取外部配置spring

ExternalPropertiesUtils.javaapache

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;
    }
}