本文為博主原創,未經允許不得轉載:
在項目的應用中,經常將一些配置放入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>