WebMvcConfigurer配置HandlerInterceptor拦截器失效

1.前言

Springboot2.0之前,实现拦截器功能的配置类是通过继承(extends)WebMvcConfigurerAdapter类完成的,最近项目把Springboot升级到了Springboot2.X,WebMvcConfigurerAdapter类已经不能使用了,查了资料说现在要通过实现(implements)WebMvcConfigurer接口来完成该功能。

这时候出现问题了,实现(implements)WebMvcConfigurer接口后,启动程序,程序运行过程中根本没走到该配置类和拦截器代码。

2.配置类WebMvcConfig

import com.xq.plugin.SecurityHandlerInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

	@Autowired
	SecurityHandlerInterceptor securityHandlerInterceptor;

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(securityHandlerInterceptor).addPathPatterns("/**");
	}
}

3.拦截器SecurityHandlerInterceptor

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class SecurityHandlerInterceptor implements HandlerInterceptor {
	private static final Log log = LogFactory.getLog(SecurityHandlerInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HandlerMethod handlerMethod = null;
		if (handler instanceof HandlerMethod) {
			handlerMethod = (HandlerMethod) handler;
		}
		if (handlerMethod == null) {
			return true;
		}

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
		if (log.isDebugEnabled()) {
			log.debug(SecurityHandlerInterceptor.class.getSimpleName() + "postHandle方法");
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		if (log.isDebugEnabled()) {
			log.debug(SecurityHandlerInterceptor.class.getSimpleName() + "afterCompletion方法");
		}
	}

}

 4.失效原因

原来SpringBoot做了这个限制,只有当WebMvcConfigurationSupport类不存在的时候才会生效WebMvc自动化配置,因为我在写swagger配置类时继承(extends)了WebMvcConfigurationSupport类,所以实现(implements)了WebMvcConfigurer接口的WebMvcConfig配置类没有生效。

原swagger配置类代码:

import com.xq.common.constants.AppConstants;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2Config extends WebMvcConfigurationSupport {
    //因为swagger与静态文件访问配置冲突,所以整合swagger需要
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        // springboot 集成swagger2.2后静态资源404,添加如下两行配置
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }

    @Bean
    public Docket customDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("xq")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.xq.yexiong.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(AppConstants.app+"的API接口")
                .version("1.0")
                .build();
    }

}

5.解决方法

解决方法很简单,就是让swagger配置类不再继承(extends)WebMvcConfigurationSupport类,也去实现(implements)WebMvcConfigurer接口即可。

新swagger配置类代码:

import com.xq.common.constants.AppConstants;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2Config implements WebMvcConfigurer {
    //因为swagger与静态文件访问配置冲突,所以整合swagger需要
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        // springboot 集成swagger2.2后静态资源404,添加如下两行配置
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        //super.addResourceHandlers(registry);
    }

    @Bean
    public Docket customDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("xq")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.xq.yexiong.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(AppConstants.app+"的API接口")
                .version("1.0")
                .build();
    }

}

6.总结

springBoot2.0以上 WebMvcConfigurerAdapter 方法过时,有两种替代方案:
1、继承WebMvcConfigurationSupport
2、实现WebMvcConfigurer
但是继承(extends)WebMvcConfigurationSupport类会让Springboot对WebMvc自动化配置失效。所以项目中不能同时使用。

参考文档:https://www.cnblogs.com/sueyyyy/p/11611676.html

 

                
  • 10
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
### 回答1: 可能是以下原因导致webmvcconfigurer不生效: 1. 没有正确配置webmvcconfigurer,需要检查代码是否正确。 2. webmvcconfigurer被其他配置覆盖了,需要检查其他配置是否有影响。 3. webmvcconfigurer的优先级不够高,需要提高优先级。 4. webmvcconfigurer的配置与实际情况不符,需要检查配置是否与实际情况相符。 需要根据具体情况进行排查和解决。 ### 回答2: 首先,我们需要明确 WebMvcConfigurer 接口的作用。它是 Spring MVC 框架提供的一个编程接口,用于对 Spring MVC 配置进行定制化。它提供了很多方法,可以用来自定义拦截器、跨域处理、视图解析器、异常处理器等等。 然而,如果 WebMvcConfigurer 不生效,通常有以下几个可能的原因: 1. 忘记在 Spring MVC 配置文件中注册 WebMvcConfigurer 在 Spring MVC 配置文件中需要通过如下方式注入 WebMvcConfigurer: ```java @EnableWebMvc @Configuration public class WebMvcConfig implements WebMvcConfigurer { //... } ``` 其中 @EnableWebMvc 注解的作用是开启 Spring MVC 的自定义配置支持,而 WebMvcConfigurer 的实现类则负责具体的配置工作。 2. 没有正确实现 WebMvcConfigurer 接口 需要注意的是,实现 WebMvcConfigurer 接口时需要重写其一些方法,比如: ```java @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { //... } @Override public void addInterceptors(InterceptorRegistry registry) { //... } //... } ``` 如果没有正确重写这些方法,配置就不会生效。 3. 被其它的配置覆盖 在 Spring MVC 配置文件中,可能有其它的配置也会对 WebMvcConfigurer 的配置造成影响。比如,我们可能会在配置文件中使用自动配置类代替手动的配置类,那么它就会覆盖我们手动实现的 WebMvcConfigurer 接口。 解决这个问题的方法可以是禁用自动配置类,或者更改它们的优先级,使得我们手动配置WebMvcConfigurer 接口早于它们执行。 以上是 WebMvcConfigurer 不生效的一些可能原因和解决方法,我们需要仔细审查配置文件,定位具体的问题,才能成功解决。 ### 回答3: WebMvcConfigurer是一个在Spring MVC应用程序中用于定制和配置WebMvc的接口。它允许开发人员注册视图控制器、格式化器、拦截器等。但是有时候会发现WebMvcConfigurer不生效,导致配置无法生效,主要有以下几个原因: 1. 配置类没有被识别 如果你使用的是JavaConfig来进行配置,那么需要确保WebMvcConfigurer的配置类被Spring容器扫描到。因此,需要在类上添加注解@Component或@Configuration,或者在配置类所在的包上添加注解@ComponentScan。 2. 配置方法没有被调用 如果在WebMvcConfigurer的实现类中添加了定制方法,比如addViewControllers()、 addResourceHandlers()等,但并没有被调用到,那么可能是因为在配置类上没有添加注解@EnableWebMvc。只有添加了@EnableWebMvc注解或继承了WebMvcConfigurerAdapter类,该类中的方法才会被调用。 3. 配置方法执行顺序的问题 WebMvcConfigurer中的方法执行顺序是由Spring MVC核心框架控制的。如果多个方法在调用中产生了冲突,那么可能会导致某些配置无法生效。这时候,可以考虑使用Ordered接口或@Order注解来控制方法的执行顺序。 4. 配置文件与代码冲突 如果在WebMvcConfigurer配置类中定义了相同的配置项,可能会导致配置无法生效。在使用JavaConfig时,应该确保配置文件中没有出现与WebMvcConfigurer类中相同的配置项。 总之,WebMvcConfigurer不生效可能是由于配置类没有被识别、配置方法没有被调用、配置方法执行顺序的问题或者配置文件与代码冲突等原因导致的。需要仔细检查配置文件和代码,确保它们都正确无误,才能使WebMvcConfigurer生效。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值