WebMvcConfigurerAdapter配置类其实是Spring内部的一种配置方式,采用JavaBean的形式来代替传统的xml配置文件形式进行针对框架个性化定制,下面我们来看一下该类内的常用方法。
WebMvcConfigurerAdapter实现类
我们创建一个配置实体类型,并继承WebMvcConfigurerAdapter,代码如下所示:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
import java.util.List;
@Configuration
public class WebConfiguration extends WebMvcConfigurerAdapter
{
}
我们在配置类上添加了注解@Configuration,标明了该类是一个配置类并且会将该类作为一个SpringBean添加到IOC容器内,我们打开该注解的源码查看如下所示:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package org.springframework.context.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.stereotype.Component;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
String value() default "";
}
可以看到在@Configuration上声明式添加了Spring注入注解@Component,所以我们配置了@Configuration会被自动添加到IOC容器内。
WebMvcConfigurerAdapter该抽象类其实里面没有任何的方法实现,只是空实现了接口WebMvcConfigurer内的全部方法,并没有给出任何的业务逻辑处理,如果我们需要针对具体的某一个方法做出逻辑处理,仅仅需要在WebMvcConfigurerAdapter子类中@Override对应方法就可以了。
配置拦截器
拦截器配置如下所示:
@Override
public void addInterceptors(InterceptorRegistry registry) {
super.addInterceptors(registry);
registry.addInterceptor(new TestInterceptor()).addPathPatterns("/**");
}
InterceptorRegistry内的addInterceptor需要一个实现HandlerInterceptor接口的拦截器实例,addPathPatterns方法用于设置拦截器的过滤路径规则。
配置CORS
配置cors(跨域资源共享)跨域访问,配置如下所示:
@Override
public void addCorsMappings(CorsRegistry registry) {
super.addCorsMappings(registry);
registry.addMapping("/cors/**")
.allowedHeaders("*")
.allowedMethods("POST","GET")
.allowedOrigins("*");
}
配置ViewController
该配置,主要是做:请求时不通过@RequestMapping配置,而是直接通过配置文件映射指定请求路径到指定View页面,配置如下所示:
@Override
public void addViewControllers(ViewControllerRegistry registry) {
super.addViewControllers(registry);
registry.addViewController("/").setViewName("/index");
//访问“../”路径时不通过@RequestMapping配置,直接通过该配置映射到“../index”页面
}
配置MessageConverter
这个配置一般针对于Api接口服务程序,配置在请求返回时内容采用什么转换器进行转换,我们最常用到的就是fastJson的转换,配置如下所示:
/**
* 消息内容转换配置
* 配置fastJson返回json转换
* @param converters
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//调用父类的配置
super.configureMessageConverters(converters);
//创建fastJson消息转换器
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
//创建配置类
FastJsonConfig fastJsonConfig = new FastJsonConfig();
//修改配置返回内容的过滤
fastJsonConfig.setSerializerFeatures(
SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.WriteMapNullValue,
SerializerFeature.WriteNullStringAsEmpty
);
fastConverter.setFastJsonConfig(fastJsonConfig);
//将fastjson添加到视图消息转换器列表内
converters.add(fastConverter);
}
内容转换都是针对面向接口进行编写的实现类,都必须implements HttpMessageConverter接口完成方法的实现。