SpringBoot中实现WebMvcConfigurer,配置跨域无效

跨域配置如下:

@Configuration public class CorsConfig implements WebMvcConfigurer {

/** * 跨域配置 * - Access-Control-Allow-Origin的介绍: * - https://blog..net/MicroAnswer/article/details/102913571 * - SpringMVC路径匹配规则: * - 1、https://wenku.baidu.com/view/508c0286b3717fd5360cba1aa8114431b90d8ec8.html * - 2、https://www.cnblogs.com/selfchange/p/spring.html * * @param registry */ @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // 允许跨域访问的路径 .allowedOrigins("http://localhost:8083") // 允许跨域访问的源 .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE") // 允许的请求方法类型 .maxAge(168000) // 预检间隔时间 .allowedHeaders("Auth-Token", "Content-Type", "Encrypt-Key", "industry-category", "business-data") // 允许头部设置 .allowCredentials(true); // 是否允许发送cookie } }

后来分析得到导致这个问题的原因是,我自定义了拦截器导致。那么,为什么自定义了拦截器就会导致上面的配置无效呢?

在SpringBoot中,SpingMVC的默认基础配置就是由WebMvcAutoConfiguration和EnableWebMvcConfiguration这两个类所定义的,为什么知道基础配置是由这两个类所定义的?

EnableWebMvcConfiguration继承了DelegatingWebMvcConfiguration。而DelegatingWebMvcConfiguration这个类会检查所有WebConfigure的实现并且获取其中定义的配置信息。主要看这段代码(就是通过@Autowired注入Spring容器中所有的WebMvcConfiguration的实例):

我自定义的拦截器是直接继承承WebMvcConfigurationSupport类并重写InterceptorConfig方法来实现的。这样就会覆盖WebMvcConfigurationSupport默认的一些子类,其中就包括EnableWebMvcConfiguration所继承的类--DelegatingWebMvcConfiguration。所以最终也就导致了我自定义的跨域配置无效。

解决方案:

错误方案:

更改自定义的跨域配置为继承DelegatingWebMvcConfiguration这个类。更改了过后还是不生效,原因是: 只要Spring上下文里存在了WebMvcConfigurationSupport类型的实例,就不会再去Spring上下文里注册WebMvcConfiguration的实例了。

注意:

WebMvcAutoConfiguration中的WebMvcAutoConfigurationAdapter会导入EnableWebMvcConfiguration的配置(这个类定义了一系列mvc的基础配置,具体有哪些配置,请查看源码)。而这个EnableWebMvcConfiguration又是继承了DelegatingWebMvcConfiguration的子类,DelegatingWebMvcConfiguration。

正确方案:

将自定义的拦截器改为 实现WebConfigure即可。

经验分享 程序员 微信小程序 职场和发展