記一次SpringMVC項目轉Springboot項目templates和static無法訪問以及WebMvcConfigurerAdapter過時失效


在這次項目升級過程中主要遇到了三個問題

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;

    @Override
    public 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下的靜態資源的引用如下

 

 

 

 

 

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM