springboot2.x使用WebMvcConfigurer替代springmvc.xml配置文件

介绍

spring boot提倡减少配置文件,使用 WebMvcConfigurer 接口代替配置文件,可以配置 静态资源映射、拦截器等功能

即保留了所有自动配置,也能用我们自定义的配置

  • 在 springboot2.x 中,要求jdk1.8,该版本的jdk支持接口中使用default方法,所以废弃WebMvcConfigurerAdapter,使用 WebMvcConfigurer 接口实现

  • 在 SpringBoot1.x 中,重写WebMvcConfigurerAdapter接口实

WebMvcConfigurer 接口

实现该接口,并且要使用 @Configuration 注解,并且不能用@EnableWebMvc注解
即保留了原有配置(静态资源路径等),又能增加功能

常用的方法:

 /* 拦截器配置 */
void addInterceptors(InterceptorRegistry var1);
/* 视图跳转控制器 */
void addViewControllers(ViewControllerRegistry registry);
/**
     *静态资源处理
**/
void addResourceHandlers(ResourceHandlerRegistry registry);
/* 默认静态资源处理器 */
void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer);
/**
     * 这里配置视图解析器
 **/
void configureViewResolvers(ViewResolverRegistry registry);
/* 配置内容裁决的一些选项*/
void configureContentNegotiation(ContentNegotiationConfigurer configurer);
/** 解决跨域问题 **/
public void addCorsMappings(CorsRegistry registry) ;

例子

package top.malaoshi.conf;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
//        访问 http://localhost:8091/test,跳转到http://localhost:8091/db
        registry.addViewController("/test").setViewName("/db");
    }
}

感谢:
https://blog.csdn.net/zhangpower1993/article/details/89016503


原文出处:/show_1EF5rGMM2dZf.html