Singleton mode read configuration file

When reading the configuration file, if we write an ordinary Java class, it may be loaded and executed multiple times when it is called. But for example, the configuration file, attribute loading, and the data are configured in advance and will not be changed frequently. We only need to load it once when we use it. Then we can use the singleton mode.

achieve this function.

package com.test.connect.hive;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Objects;
import java.util.Properties;


public  class HiveResourceInfo {

    private static HiveResourceInfo resourceInfo=null;
    private static Properties prop=null;
    private HiveResourceInfo(){}

    public static synchronized Properties getHiveConf() throws Exception {
        if(null == resourceInfo){
            resourceInfo=new HiveResourceInfo();
            InputStream inputStream = HiveResourceInfo.class
                    .getClassLoader()
                    .getResourceAsStream("connInfo/hive/hiveConf.properties");

            if (Objects.isNull(inputStream)) {
                throw new Exception("can not read connInfo/hive/hiveConf.properties");
            }
            if(null == prop){
                prop=new Properties();
            }
            prop.load(new InputStreamReader(inputStream,"UTF-8"));

        }

        return prop;
    }
}

Note: The path on the local read file and the server may be different, you need to add more'/'

Guess you like

Origin blog.csdn.net/Baron_ND/article/details/110132828