Spring配置檔案載入外部配置檔案

2021-08-02 22:00:25 字數 1438 閱讀 2930

有時,應用程式可能需要從不同的位置(例如:檔案系統、classpath或者url)讀取外部資源(例如:文字檔案、xml檔案、屬性檔案或或者影象檔案)。通常,為了從不同位置載入資源,需要和不同的api打交道。

spring的資源載入器提供了乙個統一的getresource()方法,使用這個方法可以通過資源路徑獲取外部資源。可以給路徑指定不同的字首以從不同位置載入資源。要從檔案系統載入資源,可以使用file字首,要從classpath載入資源,可以使用classpath字首,也可以在這個資源路徑裡指定url。

resource是spring裡的乙個通用介面,它代表了乙個外部資源。spring為resource介面提供了幾種實現。資源載入器的getresource()方法將根據資源路徑決定例項化哪乙個resource實現。

1.檔案系統路徑

資源路徑可以使用檔案系統的相對路徑,也可以使用絕對路徑。

file:c:/shop/banner.txt

載入d盤下的檔案

class="org.springframework.context.support.reloadableresourcebundlemessagesource">

name="basenames">

file:d:/opt/lt/xg/cfg/commonconfigurevalue>

file:d:/opt/lt/xg/cfg/messagesvalue>

file:d:/opt/lt/xg/cfg/config/configvalue>

list>

property>

name="defaultencoding">

utf-8value>

property>

bean>

2.classpath路徑

當資源位於classpath時,可以使用classpath字首。如果沒有出現路徑資訊,那麼將從classpath的根部載入資源。

classpath:banner.txt

3.除了檔案系統路徑和classpath外,資源也可以通過指定url載入。

在bean的配置裡,簡單地為resource屬性指定乙個資源路徑。spring將使用預先註冊的屬性編輯器resourceeditor將

資源轉換為resource物件,然後,再將該resource物件注入到bean裡。

spring配置檔案載入

spring配置檔案的裝載在web.xml中配置 此引數用於後面的spring context loader contextconfiglocation org.springframework.web.context.contextloaderlistener 說明 contextconfigloc...

spring載入配置檔案

在spring中載入配置檔案的方式 configuration propertysource import datasourceconfig.class bean public static propertysourcesplaceholderconfigurer propertysourcespl...

springboot 載入外部配置檔案

開發springboot應用時經常有多個配置檔案,開發的,測試的,生產環境的。而生產環境的敏感資料又不希望洩露出去,所有想看看springboot有沒有辦法載入外部檔案的辦法。因為springboot 預設載入配置檔案的位置是 classpath classpath config file file...