日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

Spring读取jar包外部的配置文件properties

發布時間:2025/7/25 javascript 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Spring读取jar包外部的配置文件properties 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

2019獨角獸企業重金招聘Python工程師標準>>>

一 。 如何獲取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的配置對應。

?

轉載于:https://my.oschina.net/u/2382040/blog/2050088

總結

以上是生活随笔為你收集整理的Spring读取jar包外部的配置文件properties的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。