Java項目properties文件的讀取

1.在自己的config.properties文件中配置自己需要用的變量參數,如:

dsp.ip=10.45.34.125
dsp.port=8888

2.寫個Util類,加入一個靜態代碼塊,在項目啓動時自動把config.properties加載進一個靜態的變量對象Properties中,然後再寫一個屬性獲取方法,獲取自己配置的參數,代碼如下:

public class PropertiesUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(PropertiesUtils.class);

    private static Properties properties=new Properties();

    static{
            //注意屬性配置文件所在的路徑
        try {
            properties.load(PropertiesUtils.class.getClassLoader().getResourceAsStream("config.properties"));
        } catch (IOException e) {
            LOGGER.error("PropertiesUtils IOException occur", e);
        }

    }

    //讀取屬性配置文件中的某個屬性對應的值
    public static String readProperty(String property){
        return (String) properties.get(property);
    }

}

3.使用:如下:

private static final String DSP_IP=PropertiesUtils.readProperty("dsp.ip");
private static final String DSP_PORT=PropertiesUtils.readProperty("dsp.port");

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章