SpringBoot 配置跨域 和版本问题

SpringBoot 配置跨域 和版本问题

使用 springboot版本:2.3.6.RELEASE、2.4.2、2.7.4

使用返回新的过滤器报错!!!

报错信息:IllegalStateException

Post-processing of merged bean definition failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class 
[org.springframework.web.cors.reactive.CorsWebFilter] from ClassLoader [sun.misc.Launcher$AppClassLoader@18b4aac2]
@Configuration
public class CorsConfig {

    //@Bean
    public CorsWebFilter corsWebFilter(){
        //1.添加CORS配置信息
        CorsConfiguration config = new CorsConfiguration();
        //放行哪些原始域
        config.addAllowedOrigin("*");
        //是否发送Cookie信息
        config.setAllowCredentials(true);
        //放行哪些原始域(请求方式)
        config.addAllowedMethod("*");
        //放行哪些原始域(头部信息)
        config.addAllowedHeader("*");
        //暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
        config.addExposedHeader("*");

        //2.添加映射路径
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);

        //3.返回新的CorsFilter.
        return new CorsWebFilter(configSource);
    }

}

使用重写WebMvcConfigurer方法后可正常启动!!!

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    static final String[] ORIGINS = new String[]{"GET", "POST", "PUT", "DELETE", "OPTIONS"};

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 所有的当前站点的请求地址,都支持跨域访问。
        registry.addMapping("/**")
                //是否发送Cookie
                .allowCredentials(true)
                //放行哪些原始域
                .allowedOrigins("*")
                //当前站点支持的跨域请求类型是什么
                .allowedMethods(ORIGINS)
                //	允许请求头中的header,默认都支持
                .allowedHeaders("*")
                //响应头中允许访问的header,默认为空
                .exposedHeaders("*")
                //预请求的结果的有效期,默认30分钟,这里为一天
                .maxAge(24 * 60 * 60);
    }
}
posted @ 2022-10-01 21:27  lam要努力  阅读(2413)  评论(0编辑  收藏  举报