java中Properties類及讀取properties中屬性值


本文為博主原創,未經允許不得轉載:

      在項目的應用中,經常將一些配置放入properties文件中,在代碼應用中讀取properties文件,就需要專門的類Properties類,通過這個類可以進行讀取。

深入理解和學習的參考的詳見:深入理解和學習Properties參考  

    此處展現在項目中讀取properties配置文件中的幫助類,代碼可以直接使用:

*******注:讀取properties文件中的屬性也可以用spring  boot中的注解來讀取,可參考我的標簽中spring boot中如何快速獲取properties中的配置屬性值  

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

public class PropertiesUtil
{

    public static final String FILE_PATH = "properties/upload.properties";

    //通過傳入的路徑及key,獲得對應的值
    public static String getValue(String path, String key)
    {
        Properties properties = new Properties();
        try
        {
            properties.load(PropertiesUtil.class.getClassLoader().getResourceAsStream(path));
        }
        catch (IOException e)
        {
            throw new RuntimeException("File Read Failed...", e);
        }
        return properties.getProperty(key);
    }
    //通過key直接獲取對應的值
    public static String getValue(String key)
    {
        Properties properties = new Properties();
        try
        {
            properties.load(PropertiesUtil.class.getClassLoader().getResourceAsStream(FILE_PATH));
        }
        catch (IOException e)
        {
            throw new RuntimeException("File Read Failed...", e);
        }
        return properties.getProperty(key);
    }

}

 另外還需要在spring配置文件中,對屬性文件在項目啟動的時候進行初始化加載和解析:代碼如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
       http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <bean id="configHelper" class="com.allcam.system.utils.ConfigHelper"
        init-method="init"> <!--進行初始化加載-->
    </bean>

    
</beans>

 


免責聲明!

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



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