springboot 運(yùn)行 jar 包讀取外部配置文件的問題
案例:本文主要描述linux系統(tǒng)執(zhí)行jar包讀取jar包同級目錄的外部配置文件方法一:相對路徑設(shè)置配置文件(1)在jar包同級目錄創(chuàng)建配置文件conf.properties并寫入配置數(shù)據(jù):
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();//獲取配置文件數(shù)據(jù)String confData = properties.getProperty('confData');System.out.println(confData); }}
(3)執(zhí)行jar包
java -jar jarNanexxx
方法二:絕對路徑設(shè)置配置文件解決問題:使用相對路徑的方法在jar包同級目錄手動執(zhí)行jar包時沒有問題,但使用linux系統(tǒng)的crontab文件定時調(diào)度時報錯,原因:因?yàn)槲覀兪謩訄?zhí)行某個腳本時,是在當(dāng)前shell環(huán)境下進(jìn)行的,程序能找到環(huán)境變量;而系統(tǒng)自動執(zhí)行任務(wù)調(diào)度時,除了默認(rèn)的環(huán)境,是不會加載任何其他環(huán)境變量的。因此就需要在crontab文件中指定任務(wù)運(yùn)行所需的所有環(huán)境變量,或者在程序中使用絕對路徑。(1)在jar包同級目錄創(chuàng)建配置文件conf.properties并寫入配置數(shù)據(jù):
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();//獲取配置文件數(shù)據(jù)String confData = properties.getProperty('confData');System.out.println(confData); }}
(3)執(zhí)行jar包
java -jar jarNanexxx
到此這篇關(guān)于springboot 運(yùn)行 jar 包讀取外部配置文件的文章就介紹到這了,更多相關(guān)springboot 配置文件內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ASP新手必備的基礎(chǔ)知識2. asp文件用什么軟件編輯3. Docker 啟動Redis 并設(shè)置密碼的操作4. CentOS郵箱服務(wù)器搭建系列——SMTP服務(wù)器的構(gòu)建( Postfix )5. PHP基礎(chǔ)之生成器4——比較生成器和迭代器對象6. JS中6個對象數(shù)組去重的方法7. vue+element開發(fā)一個谷歌插件的全過程8. Vue axios獲取token臨時令牌封裝案例9. 通過IEAD+Maven快速搭建SSM項(xiàng)目的過程(Spring + Spring MVC + Mybatis)10. 利用CSS制作3D動畫

網(wǎng)公網(wǎng)安備