通过实现 WebMvcConfigurer ,推荐,不能配置多个,只能配置一个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
   | package com.example;
  import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  @Configuration public class CorsConfig implements WebMvcConfigurer {     @Override     public void addCorsMappings(CorsRegistry registry) {         registry.addMapping("/**")                 .allowedOrigins("*")                 .allowedHeaders("*")                 .allowedMethods("*");     } }
   | 
 
通过过滤器配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
   | @Configuration public class CorsConfig {     @Bean     CorsWebFilter corsWebFilter(){         UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();         CorsConfiguration config = new CorsConfiguration();                  config.addAllowedHeader("*");                  config.addAllowedMethod("*");                  config.addAllowedOrigin("*");                  config.setAllowCredentials(true);
                   source.registerCorsConfiguration("/**", config);         return new CorsWebFilter(source);     } }
   |