美文网首页
springboot配置拦截器不生效解决办法

springboot配置拦截器不生效解决办法

作者: 拄杖忙学轻声码 | 来源:发表于2021-08-28 22:59 被阅读0次

问题描述和原因分析:
如果我们同时配置一个类继承 WebMvcConfigurationSupport 和 一个类实现 WebMvcConfigurer 这样就会出现只有配置类继承 WebMvcConfigurationSupport 才生效,就会导致我们配置的拦截器不生效,如下:

继承:WebMvcConfigurationSupport

package com.hkl.configure;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
 
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer contentNegotiationConfigurer){
        contentNegotiationConfigurer
//                .favorPathExtension(true)   //是否支持后缀的方式
//                .favorParameter(true)     //是否支持请求参数的方式
//                .parameterName("format")  //请求参数名
                .defaultContentType(MediaType.APPLICATION_JSON); //默认返回格式
    }
}

实现:WebMvcConfigurer

package com.hkl.intercept;
 
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
import javax.annotation.Resource;
 
@Configuration
@Slf4j
public class WebMvcAddIntercepter implements WebMvcConfigurer {
    @Resource
    private GlobalWebMvcIntercepter globalWebMvcIntercepter;
 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry
                .addInterceptor(globalWebMvcIntercepter)
                .addPathPatterns("/**");    //拦截路径
//                .excludePathPatterns();     //不拦截路径
        WebMvcConfigurer.super.addInterceptors(registry);
    }
}

如果在项目中多个类同时继承 WebMvcConfigurationSupport 和实现 WebMvcConfigurer的情况,将会导致只有 WebMvcConfigurationSupport 生效
解决办法:将这些配置都在一个类中设置,将代码整合至一个类中或者删除 WebMvcConfigurationSupport 配置,拦截器才会生效

相关文章

网友评论

      本文标题:springboot配置拦截器不生效解决办法

      本文链接:https://www.haomeiwen.com/subject/wsxwiltx.html