Spring讀取jar包外部的配置檔案properties
阿新 • • 發佈:2018-12-02
一 。 如何獲取jar包外的檔案?
新專案用jar包執行,直接需求就是讀取jar外部的配置檔案properties,做到不同的環境有不同的配置資訊。
用Spring管理的話
<context:property-placeholder ignore-unresolvable="true" location=" classpath:config/database.properties, classpath:config/voiceapi.properties, classpath:config/threadpool.properties, file:${user.dir}/override.properties"/>
需要2點:
1.file:協議
2.${user.dir} ,來自jdk的 System.getProperty("user.dir") ,會輸出專案的本地路徑
二。 如何檔案流?
public static String getProperties(String keyWord) { InputStream is = PropertiesProvider.class.getClassLoader().getResourceAsStream("config/error.properties"); BufferedReader br = new BufferedReader(new InputStreamReader(is,Charset.forName("utf-8"))); Properties properties = new Properties(); try { properties.load(br); return properties.getProperty(keyWord); } catch (IOException e) { e.printStackTrace(); } return null; }
最合理的程式碼。推薦使用。如果用file 取讀,會遇到jar包路徑獲取不到的問題。
三。如何獲取檔案路徑?
當專案裡需要讀取配置檔案,有相對路徑和絕對路徑之分。絕對路徑存在無法遷移,適配性不高的問題,只討論相對路徑
java不會支援獲取.java檔案的路徑,只能依靠根據.class檔案獲取相對路徑
Producer.class.getResource("config/kafka.properties").getPath();
1.配置檔案肯定需要統一管理, 通常在resource檔案下
2.配置pom.xml,讓maven打包的時候加入resource目錄
<!--管理配置檔案打包--> <resources> <resource> <!--需要打包的目錄--> <directory>${basedir}/src/main/resources</directory> <!--打包後的目錄,預設是根目錄--> <!--<targetPath>src/main/resources</targetPath>--> <filtering>false</filtering> </resource> </resources>
3.程式裡
static { properties = new Properties(); String path = Producer.class.getResource("/config/kafka.properties").getPath(); try { FileInputStream fis = new FileInputStream(new File(path)); properties.load(fis); } catch (Exception e) { e.printStackTrace(); } }
getResource方法的邏輯,如果是斜槓 / 符號開頭,就是根目錄找,這裡和pom.xml的配置對應。