1. 程式人生 > >Springboot 靜態資源路徑配置的兩種方法

Springboot 靜態資源路徑配置的兩種方法

參考學習:
http://www.zslin.com/web/article/detail/23
http://blog.csdn.net/catoop/article/details/50501706

訴求:Spring Boot 預設為我們提供了靜態資源處理,而有時我們需要自定義資源對映,可定義專案內部目錄,也可定義外部目錄。此處舉例外部目錄對映配置。

方法一:通過配置檔案配置

在Springboot中可以直接在配置檔案中覆蓋預設的靜態資源路徑的配置資訊:
作用在application.yml或application.properties
首先系統有預設配置,其中預設配置的 /** 對映到 /static (或/public、/resources、/META-INF/resources)

預設大概意思如下所示(為了和下面進行對比):
spring:
    mvc:
        static-path-pattern: /**
    resources:
         static-locations: classpath:/META-INF/resources/,classpath:/resources/, classpath:/static/, classpath:/public/

定義 static-path-pattern: /** ,會覆蓋預設配置,需要在static-locations新增預設的內部目錄和自定義目錄,應為

新增自定義外部目錄並覆蓋預設
spring:
    mvc:
        static
-path-pattern: /** http: multipart: location: F://preview resources: static-locations: classpath:/META-INF/resources/,classpath:/resources/, classpath:/static/, classpath:/public/, file:${spring.http.multipart.location}

如果定義 static-path-pattern: /we/**,則訪問static-locations裡目錄時都應加上”/we/”
spring.mvc.static-path-pattern 只可以定義一個,目前不支援多個逗號分割的方式,

方法二:通過@Configuration配置

@Configuration
public class ApplicationConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /**
         * 如果我們將/xxxx/** 修改為 /** 與預設的相同時,則會覆蓋系統的配置,可以多次使用 addResourceLocations 新增目錄,
         * 優先順序先新增的高於後新增的。
         *
         * 如果是/xxxx/** 引用靜態資源 加不加/xxxx/ 均可,因為系統預設配置(/**)也會作用
         * 如果是/** 會覆蓋預設配置,應用addResourceLocations新增所有會用到的靜態資源地址,系統預設不會再起作用
         */
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/META-INF/resources/")
                .addResourceLocations("classpath:/resources/")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/public/");
        registry.addResourceHandler("/we/**").addResourceLocations("file:F:/preview/");
        super.addResourceHandlers(registry);
    }
}

此方法直接寫在程式碼內,同方法一一樣,可以覆蓋預設配置,新增自定義對映配置,也可以只新增自定義對映配置,不覆蓋預設配置。方法二比之方法一更為靈活。