解決springboot 2.x 里面訪問靜態(tài)資源的坑
springboot 2.x 里面訪問靜態(tài)資源的坑
在spring boot的自定義配置類繼承 WebMvcConfigurationSupport 后,發(fā)現(xiàn)自動配置的靜態(tài)資源路徑
classpath:/META/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
不生效。
首先看一下 自動配置類的定義:
這是因為在 springboot的web自動配置類 WebMvcAutoConfiguration 上有條件注解
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
這個注解的意思是在項目類路徑中 缺少 WebMvcConfigurationSupport類型的bean時改自動配置類才會生效,所以繼承 WebMvcConfigurationSupport 后需要自己再重寫相應(yīng)的方法。
如果想要使用自動配置生效
又要按自己的需要重寫某些方法,比如增加 viewController ,則可以自己的配置類可以繼承 WebMvcConfigurerAdapter 這個類。不過在spring5.0版本后這個類被丟棄了 WebMvcConfigurerAdapter ,雖然還可以用,但是看起來不好。
/** * 原來是這么寫的: * public class BeanConfiguration extends WebMvcConfigurationSupport * 導(dǎo)致默認配置的靜態(tài)資源不生效了 */ @Configuration public class BeanConfiguration implements WebMvcConfigurer { @Bean public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); mapper.setTimeZone(TimeZone.getTimeZone("GMT+8")); mapper.setDefaultPropertyInclusion(JsonInclude.Include.ALWAYS); converter.setObjectMapper(mapper); return converter; } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { //將我們定義的時間格式轉(zhuǎn)換器添加到轉(zhuǎn)換器列表中, //這樣jackson格式化時候但凡遇到Date類型就會轉(zhuǎn)換成我們定義的格式 converters.add(jackson2HttpMessageConverter()); // 添加字符串轉(zhuǎn)換,否認如果返回字符串,則會報異常,其他converter // 參考:org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport#addDefaultHttpMessageConverters StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(); stringHttpMessageConverter.setWriteAcceptCharset(false); // see SPR-7316 converters.add(stringHttpMessageConverter); } }
SpringBoot2.x過后static下的靜態(tài)資源無法訪問
package com.example.thymeleaf.commons; import org.springframework.stereotype.Component; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * 配置靜態(tài)資源映射 * * @author sunziwen * @version 1.0 * @date 2018-11-16 14:57 **/ @Component public class WebMvcConfig implements WebMvcConfigurer { /** * 添加靜態(tài)資源文件,外部可以直接訪問地址 * * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); } }
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
JAVA編程實現(xiàn)UDP網(wǎng)絡(luò)通訊的方法示例
這篇文章主要介紹了JAVA編程實現(xiàn)UDP網(wǎng)絡(luò)通訊的方法,簡單說明了UDP通訊的原理并結(jié)合實例形式分析了java實現(xiàn)UDP通訊的相關(guān)類與使用技巧,需要的朋友可以參考下2017-08-08idea2020.1最新版永久破解/pycharm也可用(步驟詳解)
這篇文章主要介紹了idea2020.1最新版永久破解/pycharm也可用,本文給大家分享簡單實現(xiàn)步驟,通過圖文并茂的形式給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-04-04