springboot 運行 jar 包讀取外部配置文件的問題
案例:本文主要描述linux系統執行jar包讀取jar包同級目錄的外部配置文件方法一:相對路徑設置配置文件(1)在jar包同級目錄創建配置文件conf.properties并寫入配置數據:
confData=data
(2)開始寫入自動化測試代碼
//from www.fhadmin.cnpublic class Test{ public String getData() throws IOException {//讀取配置文件Properties properties = new Properties();File file = new File('conf.properties');FileInputStream fis = new FileInputStream(file);properties.load(fis);fis.close();//獲取配置文件數據String confData = properties.getProperty('confData');System.out.println(confData); }}
(3)執行jar包
java -jar jarNanexxx
方法二:絕對路徑設置配置文件解決問題:使用相對路徑的方法在jar包同級目錄手動執行jar包時沒有問題,但使用linux系統的crontab文件定時調度時報錯,原因:因為我們手動執行某個腳本時,是在當前shell環境下進行的,程序能找到環境變量;而系統自動執行任務調度時,除了默認的環境,是不會加載任何其他環境變量的。因此就需要在crontab文件中指定任務運行所需的所有環境變量,或者在程序中使用絕對路徑。(1)在jar包同級目錄創建配置文件conf.properties并寫入配置數據:
confData=data
(2)開始寫入自動化測試代碼
//from www.fhadmin.cnpublic class Test{ public String getData() throws IOException { //獲取jar包同級目錄String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();String[] pathSplit = path.split('/');String jarName = pathSplit[pathSplit.length - 1];String jarPath = path.replace(jarName, '');String pathName=jarPath+'minhang.properties';System.out.println('配置文件路徑:'+jarPath);//讀取配置文件Properties properties = new Properties();File file = new File(pathName);FileInputStream fis = new FileInputStream(file);properties.load(fis);fis.close();//獲取配置文件數據String confData = properties.getProperty('confData');System.out.println(confData); }}
(3)執行jar包
java -jar jarNanexxx
到此這篇關于springboot 運行 jar 包讀取外部配置文件的文章就介紹到這了,更多相關springboot 配置文件內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
