• java 读取properties配置文件


    目录结构:

    1. 首先有个一主配置文件:custom.properties,主要用于加载全局的,不区分开发环境的配置,里面必须包含一个属性profiles.active(区分加载哪个配置);

    2. 创建一个 custom-xxx.properties 的配置文件,在主配置文件中设置 profiles.active=xxx 即可加载 custom-xxx.properties 的配置,主要用于区分开发环境;

    3. Tools.isBlank() 方法可看 https://www.cnblogs.com/lixingwu/p/7113591.html ;

    4. 使用方法可查看main方法。

    package com.zhwlt.logistics.utils;
    
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;
    
    /**
     * 读取properties文件
     *
     * @author lixingwu
     */
    public class PropertiesUtils {
        private Properties properties;
        private Properties propertiesCustom;
        private static PropertiesUtils propertiesUtils = new PropertiesUtils();
    
        /**
         * 私有构造,禁止直接创建
         */
        private PropertiesUtils() {
            // 读取配置启用的配置文件名
            properties = new Properties();
            propertiesCustom = new Properties();
            InputStream in = PropertiesUtils.class.getClassLoader().getResourceAsStream("custom.properties");
            try {
                properties.load(in);
                // 加载启用的配置
                String property = properties.getProperty("profiles.active");
                if (!Tools.isBlank(property)) {
                    InputStream cin = PropertiesUtils.class.getClassLoader().getResourceAsStream("custom-" + property + ".properties");
                    propertiesCustom.load(cin);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        /**
         * 获取单例
         *
         * @return PropertiesUtils
         */
        public static PropertiesUtils getInstance() {
            if (propertiesUtils == null) {
                propertiesUtils = new PropertiesUtils();
            }
            return propertiesUtils;
        }
    
        /**
         * 根据属性名读取值
         * 先去主配置查询,如果查询不到,就去启用配置查询
         *
         * @param name 名称
         */
        public String getProperty(String name) {
            String val = properties.getProperty(name);
            if (Tools.isBlank(val)) {
                val = propertiesCustom.getProperty(name);
            }
            return val;
        }
    public static void main(String[] args) {
            PropertiesUtils pro = PropertiesUtils.getInstance();
            String value = pro.getProperty("custom.properties.name");
            System.out.println(value);
        }
    }
  • 相关阅读:
    (转)了解JNDI
    java.lang.ClassNotFoundException: com.mysql.jdbc.Driver问题
    占个座
    关于 inode 与 iblock 的知识
    机器学习性能度量指标:ROC曲线、查准率、查全率、F1
    编译出现的问题解决
    二分查找(Binary Search)
    ST算法 Sliding Window algorithm template
    数据结构_算法
    知识点积累
  • 原文地址:https://www.cnblogs.com/lixingwu/p/9249120.html
Copyright © 2020-2023  润新知