1. 程式人生 > >Spring Boot 通過 UrlResource 載入 classpath 拋 unknown protocol: classpath

Spring Boot 通過 UrlResource 載入 classpath 拋 unknown protocol: classpath

開發十年,就只剩下這套架構體系了! >>>   

自定義的配置檔案放在 resources 資料夾下,用 org.springframework.core.io.UrlResource 讀取,路徑用 classpath: 方式。普通 spring 專案沒問題,spring boot 打 war 包也可以,但啟動 Application 時就拋異常了:java.net.MalformedURLException: unknown protocol: classpath。目測這種啟動方式,不支援 classpath: 這種資源定位,於是找了新的方式代替:org.springframework.util.ResourceUtils。

舊程式碼:

	UrlResource urlResource = new UrlResource("classpath:xxx/xxx.properties");
	Properties prop = new Properties();
	prop.load(urlResource.getInputStream());
	//省略獲取prop屬性部分

新程式碼:

	File file = ResourceUtils.getFile(CONSTANT_PROPERTIES);
	Properties prop = new Properties();
	InputStream is = new FileInputStream(file);
	//省略獲取prop屬性部分

	prop.load(is);
	is.close();
<