前言
在使用Spring Boot 2.x开发的时候,我写了一个拦截器,发现不起作用,如下是我的部分代码
- 我的启动类
@SpringCloudApplication
@MapperScan("cn.com.jstec.open.system.api.mapper")
@ComponentScans({
@ComponentScan("cn.com.jstec.open.system.api")
})
@EnableFeignClients
@EnableHystrix
public class ConsoleApplication {
}
- 我的配置
@Slf4j
@Configuration
public class WebConf implements WebMvcConfigurer {
@Bean
public LoginInterceptor getLoginInterceptor() {
return new LoginInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
log.info("添加登录拦截器");
//添加登录拦截器
registry.addInterceptor(getLoginInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/error", "/static/**", "/webjars/**");
}
}
目前两种方式就是通过实现WebMvcConfigurer和继承WebMvcConfigurationSupport
- 拦截器
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
}
通过启动后,无法看到拦截器生效!
解决过程
网络查询
通过查询网络资源,发现很多人都遇到这样的问题,但是对比后发现,他们的问题和我的不一样,必要的注解都已经添加了,而且目录结构也正常,组件扫描也可以扫描到。
突然发现
我为了本地测试方便,我添加了跨域处理,这个一般都是由网关完成的。查看跨域配置如下:
@Configuration
public class CorsConfig extends WebMvcConfigurationSupport {
/**
* 解决 swagger静态资源无法访问的问题
*
* @param registry
*/
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "POST", "DELETE", "PUT")
.maxAge(3600);
}
}
也就是说,我配置了2个配置类。WebMvcConfigurationSupport中那些子类可以重写的空方法在WebMvcConfigurer都有,这说明WebMvcConfigurer只是WebMvcConfigurationSupport的一个扩展类。
查看自动配置类:
@Configuration(
proxyBeanMethods = false
)
@ConditionalOnWebApplication(
type = Type.SERVLET
)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
@AutoConfigureOrder(-2147483638)
@AutoConfigureAfter({DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class})
public class WebMvcAutoConfiguration {
}
中指定了@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})也就是说明我们之前的跨越配置文件修改了默认配置,导致其他配置文件失效。
解决
- 拦截器和跨域配置在一个配置中完成
- 删除跨域配置
按照上面的解决方法,程序正常运行,可以跳转到拦截器中了!
本文深入探讨了在SpringBoot2.x环境下,拦截器不生效的问题及解决方案。作者通过对比网络资源,发现跨域配置与拦截器配置冲突,导致拦截器失效。最终通过调整配置,实现了拦截器的正确工作。
3万+

被折叠的 条评论
为什么被折叠?



