Java web系统启动时,静态初始化配置文件

    

    该工具类可以根据正则规则,去遍历查找配置文件,并静态初始化,可以在任意地方用PropUtil.get(key)方法方便的获取配置文件里的值。


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
import java.util.regex.Pattern;

/**
 * 配置文件工具类
 *
 * @author Luo Yong
 * @date 2014-03-12
 */
public final class PropUtil {

    private static final Logger LOG = LoggerFactory.getLogger(PropUtil.class.getName());
    /** FIXME 找扩展名为properties的文件*/
    private static final String REGEX_PROPERTIES = "^(.*).properties$";
    /** 查找文件的匹配正则*/
    private static final Pattern PATTERN_PROPERTIES = Pattern.compile(REGEX_PROPERTIES);
    private static Properties properties = new Properties();
    private static ClassLoader classLoader = getDefaultClassLoader();

    static {
        init();
    }

    /**
     * 获取配置文件
     *
     * @param key
     * @return
     */
    public static String get(final String key) {
        return getProperties().getProperty(key);
    }

    /**
     * 获取配置文件,为空时,返回默认值
     *
     * @param key
     * @param defaultValue
     * @return
     */
    public static String get(final String key, final String defaultValue) {
        String value = getProperties().getProperty(key);
        if (value == null || value.trim().isEmpty()) {
            return defaultValue;
        }
        return value;
    }

    private static Properties getProperties() {
        return properties;
    }

    /**
     * 初始化配置文件
     */
    private static void init() {
        // 获取classpath
        String classpath = getClasspath();
        if (classpath != null) {
            // 从classpath的父节点开始查找
            File baseDir = new File(classpath).getParentFile();
            loadDir(baseDir);
        }
    }

    /**
     * 获取classpath
     */
    private static String getClasspath() {
        String classpath = null;
        try {
            classpath = classLoader.getResource("/").getPath();
        } catch (Exception e) {
            try {
                classpath = classLoader.getResource("").getPath();
            } catch (Exception ex) {
                LOG.error(" classpath 初始化失败:", ex);
            }
        }
        return classpath;
    }

    /**
     * copy from org.springframework.util.ClassUtils
     */
    private static ClassLoader getDefaultClassLoader() {
        ClassLoader cl = null;
        try {
            cl = Thread.currentThread().getContextClassLoader();
        } catch (Exception ex) {
            LOG.error(" Thread.currentThread() 获取 ClassLoader 出错:", ex);
        }
        if (cl == null) {
            cl = PropUtil.class.getClassLoader();
            if (cl == null) {
                try {
                    cl = ClassLoader.getSystemClassLoader();
                } catch (Exception ex) {
                    LOG.error(" ClassLoader.getSystemClassLoader() 获取 ClassLoader 出错:", ex);
                }
            }
        }
        return cl;
    }

    /**
     * 递归查找配置文件<br/>
     *
     * @param baseDir 查找的文件夹
     */
	private static void loadDir(File baseDir) {
		// 判断目录是否存在
		if (!baseDir.exists() || !baseDir.isDirectory()) {
			return;
		}
		String tempPath;
		File[] files = baseDir.listFiles();
		for (File file : files) {
			if (file.isFile()) {
				tempPath = file.getAbsolutePath();
				if (PATTERN_PROPERTIES.matcher(tempPath).matches()) {
					// 匹配成功,将文件路径添加到结果集
					load(file);
				}
			} else if (file.isDirectory()) {
				loadDir(file);
			}
		}
	}

    /**
     * 读取配置文件
     *
     * @param file
     */
    private static void load(File file) {
        try (InputStream is = new FileInputStream(file);
             InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8)) {
            getProperties().load(isr);
        } catch (IOException e) {
            throw new RuntimeException("读取配置文件" + file.getName() + "出现异常", e);
        }
    }

    /**
     * 通过配置文件路径和名称,热加载Properties
     */
    public static void load(String propsName) {
        try (InputStream is = classLoader.getResourceAsStream(propsName)) {
            getProperties().load(is);
        } catch (IOException e) {
            throw new RuntimeException("读取配置文件" + propsName + "出现异常", e);
        }
    }

    private PropUtil() {
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值