javascript
Spring读取jar包外部的配置文件properties
2019獨角獸企業(yè)重金招聘Python工程師標準>>>
一 。 如何獲取jar包外的文件?
新項目用jar包運行,直接需求就是讀取jar外部的配置文件properties,做到不同的環(huán)境有不同的配置信息。
用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:協(xié)議?
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 取讀,會遇到j(luò)ar包路徑獲取不到的問題。
三。如何獲取文件路徑?
當項目里需要讀取配置文件,有相對路徑和絕對路徑之分。絕對路徑存在無法遷移,適配性不高的問題,只討論相對路徑
java不會支持獲取.java文件的路徑,只能依靠根據(jù).class文件獲取相對路徑
Producer.class.getResource("config/kafka.properties").getPath();
1.配置文件肯定需要統(tǒng)一管理, 通常在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的配置對應(yīng)。
?
轉(zhuǎn)載于:https://my.oschina.net/u/2382040/blog/2050088
總結(jié)
以上是生活随笔為你收集整理的Spring读取jar包外部的配置文件properties的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【WPF】拖拽ListBox中的Item
- 下一篇: 苹果手机(ios)拍照上传图片旋转90度