記一次SpringMVC專案轉Springboot專案templates和static無法訪問以及WebMvcConfigurerAdapter過時失效
阿新 • • 發佈:2020-07-27
在這次專案升級過程中主要遇到了三個問題
1、使用Spring5.xx(或者Springboot2.xx)版本來配置WebMVC時,發現WebMvcConfigurerAdapter不能使用,檢視原始碼後發現官方已經廢棄了這個抽象類,
現在官方在原始碼中推薦的方式是直接實現WebMvcConfigurer 這個介面,通過檢視這個介面的原始碼發現,在介面中的每個方法前都添加了“default”
在這裡說明下“default”是jdk8後的新特性,在這裡簡要說明下它與抽象類的區別,詳細的請查閱相關資料。 default方法作用範圍是public,只是有了具體實現的方法體。對已有的介面,如果想對介面增加一個新方法,那麼需要對所有實現該介面的類進行修改。 而有了default方法,可以解決該問題,但是需要注意的是public抽象類的abstract method還可以可以是protected,因此在一些方面並不能完全取代抽象類。
在WebMvcConfigurerAdapter中的每個方法都是public的,所以官方可能為了減少程式碼量,直接在WebMvcConfigurer介面中使用了default
以下時在配置WebMVC的程式碼
@Configuration // 等價於<mvc:annotation-driven/> @EnableWebMvc public class MvcConfiguration implements WebMvcConfigurer, ApplicationContextAware { // Spring容器 private ApplicationContext applicationContext; @Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; }
除了官方推薦的這種方法外,還有第二種方法就是extends WebMvcConfigurationSupport,但是使用這種方法相當於覆蓋了@EnableAutoConfiguration裡的所有方法,每個方法都需要重寫,比如,若不實現方法addResourceHandlers(),則會導致靜態資源無法訪問,因此需要特別注意。
2、templates和static無法訪問,需要在WebMVC中做如下配置
/** * 靜態資源配置 * * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/"); registry.addResourceHandler("/templates/**").addResourceLocations("classpath:/templates/"); //如果有templates就解析成類路徑下的templates registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); //如果有static就解析成類路徑下的static // 如果有upload就解析成外部的路徑file:/home/o2o/image/upload registry.addResourceHandler("upload/**").addResourceLocations("file:/home/o2o/image/upload"); }
templates與static的區別通過查閱springboot的相關文件就可以知道,這裡不在解釋
如果static中的資源還是無法訪問就去檢視你的templates下的html頁面裡面的對於static下面的靜態資源的引用路徑是否正確,
我的目錄層次結構,以及對static下的靜態資源的引用如下