java代碼如何讀取properties文件


我們在開發工程中,有時候需要在Java代碼中定義一些在部署生產環境時容易改變的變量,還需要我們單獨放在一個外部屬性文件中,方便我們將來修改。這里列出了兩種比較方便的方式。

 

一、在Spring配置文件中使用 util:properties 標簽進行暴露 properties 文件中的內容,需要注意的是需要在Spring的配置文件的頭部聲明以下部分。

xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"

1. 在classpath路徑下新建 config.properties 內容如下:

app.id=appId

2. 修改Spring的配置文件

<util:properties id="appConfig" location="classpath:config.properties"></util:properties>

3. 在需要調用的類中聲明全局變量,加上@Value注解

@Value("#{appConfig['app.id']}")
private String appId;

 

二、使用Java的Properties類

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * properties文件獲取工具類
 */
public class PropertyUtil {
    
    private static Properties props;
    static {
        loadProps();
    }

    synchronized static private void loadProps(){
        System.out.println("開始加載properties文件內容.......");
        props = new Properties();
        InputStream in = null;
        try {
            // 第一種,通過類加載器進行獲取properties文件流-->
            in = PropertyUtil.class.getClassLoader().getResourceAsStream("db.properties");
            // 第二種,通過類進行獲取properties文件流-->
            //in = PropertyUtil.class.getResourceAsStream("/jdbc.properties");
            props.load(in);
        } catch (FileNotFoundException e) {
            System.out.println("jdbc.properties文件未找到");
        } catch (IOException e) {
            System.out.println("出現IOException");
        } finally {
            try {
                if(null != in) {
                    in.close();
                }
            } catch (IOException e) {
                System.out.println("jdbc.properties文件流關閉出現異常");
            }
        }
        System.out.println("加載properties文件內容完成...........");
        System.out.println("properties文件內容:" + props);
    }

    /**
     * 根據key獲取配置文件中的屬性
     */
    public static String getProperty(String key){
        if(null == props) {
            loadProps();
        }
        return props.getProperty(key);
    }

    /**
     * 根據key獲取配置文件中的屬性,當為null時返回指定的默認值
     */
    public static String getProperty(String key, String defaultValue) {
        if(null == props) {
            loadProps();
        }
        return props.getProperty(key, defaultValue);
    }
}

測試:

String appId = PropertyUtil.getProperty("app.id");
System.out.println("appId = " + appId);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM