Springboot 使用越來越多,企業的基本框架,到Springcloud分布式,可以說無論面試還是平常技術學習,一說到spring幾乎就就代替了Java,可以說spring,springboot的力量之強大;
今天的主角是WebMvcConfigurer :
這個接口很重要,如果一個項目沒有攔截器,想想就可怕,小編也是遇到過類似的問題:
這個接口主要功能如下:
configureDefaultServletHandling:默認靜態資源處理器
configureContentNegotiation:配置內容裁決的一些參數
configureMessageConverters:信息轉換器
要記住你學到的每個接口的名稱,因為別人問你,能夠准確說出名字也很重要,本人覺得這個接口的重點是:跨域,攔截器,靜態資源處理器,信息轉化器,最好能記住;
在Spring Boot 1.5版本都是靠重寫WebMvcConfigurerAdapter的方法來添加自定義攔截器,消息轉換器等。SpringBoot 2.0 后,該類被標記為@Deprecated(棄用)。官方推薦直接實現WebMvcConfigurer或者直接繼承WebMvcConfigurationSupport,方式一實現 WebMvcConfigurer接口(推薦),方式二繼承WebMvcConfigurationSupport類,具體實現可看這篇文章。https://blog.csdn.net/fmwind/article/details/82832758
寫本文時springboot最新版本是2.2.5 官網:https://spring.io/projects/spring-boot
例子:
package com.olive.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* WebMvcConfigurer
*
*/
@Configuration
@EnableWebMvc
public class ConfigurerAdapter implements WebMvcConfigurer {
//圖片保存路徑
public static final String PIC_PATH = "/landscape/";
@Value(value="${application.profile}")
private String profile;
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowCredentials(true)
.allowedHeaders("*")
.allowedOrigins("*")
.allowedMethods("GET","POST","PUT","DELETE");
}
// 可解決Long 類型在 前端精度丟失的問題, 如不想全局 直接添加注解 @JsonSerialize(using= ToStringSerializer.class) 到相應的字段
// @Override
// public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//
// MappingJackson2HttpMessageConverter jackson2HttpMessageConverter =
// new MappingJackson2HttpMessageConverter();
//
// ObjectMapper objectMapper = new ObjectMapper();
// SimpleModule simpleModule = new SimpleModule();
// simpleModule.addSerializer(BigInteger.class, ToStringSerializer.instance);
// simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
// simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
// objectMapper.registerModule(simpleModule);
// jackson2HttpMessageConverter.setObjectMapper(objectMapper);
// converters.add(jackson2HttpMessageConverter);
// converters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
// }
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/").setCachePeriod(0);
/** 圖片傳路徑 */
registry.addResourceHandler("/landscape/**").addResourceLocations("file:" + profile);
}
}
這個類實現了WebMvcConfigurer 接口,這個類是我在搭建框架的時候,直接運用在生產的所以可以直接copy走;先到這結束。。。。