原始代码
/**
* <p>Description:跨域请求配置类</p>
* @author:gusong
* @date:2019/4/1 19:59
*/
@Configuration
public class CorsConfig {
/**
* <p>Description:配置允许跨域访问</p>
* @return:org.springframework.web.cors.CorsConfiguration
* @author:gusong
* @date:2019/4/1 20:01
*/
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
return corsConfiguration;
}
/**
* <p>Description:跨域过滤器</p>
* @return:CorsFilter
* @author:gusong
* @date:2019/4/1 20:02
*/
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
新代码
@Configuration
public class CorsConfig {
@Value("${spring.profiles.active}")
private String HSAY_ENV;
private final String[] env = new String[]{"dev","release"};
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
//允许任何域名[多行]
corsConfiguration.addAllowedOrigin("*");
//允许任何头
corsConfiguration.addAllowedHeader("*");
//允许任何方法
corsConfiguration.addAllowedMethod("*");
// 3.允许ajax异步请求带cookie信息
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}
@Bean
public FilterRegistrationBean corsFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//注册
if(Arrays.asList(env).contains(HSAY_ENV)) {
source.registerCorsConfiguration("/**", buildConfig());
}
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
// 这个顺序很重要,为避免麻烦请设置在最前
bean.setOrder(0);
return bean;
}
}
对比
对比发现什么问题了么?没错就是corsFilter这个方法的返回值。以及对于bean的设置问题,因为是偶发的所以猜到肯定和加载顺序有关系。