springcloud跨域(分环境)解决方案
配置类
CorsConfig.java
.package com.test.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author Scen
* @date 2019-05-27 17:25
*/
@Configuration
@ConditionalOnProperty(name = "open.cors", havingValue = "true")
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
// 设置允许跨域的路径
registry.addMapping("/**")
// 设置允许跨域请求的域名
.allowedOrigins("*")
// 是否允许证书 不再默认开启
.allowCredentials(true)
// 设置允许的方法
.allowedMethods("*")
// 跨域允许时间
.maxAge(7200);
}
}
其中
@ConditionalOnProperty(name = "open.cors", havingValue = "true")
name属性是从配置文件application.properties或者配置中心添加的,测试服务器配置true允许跨域,
生产服务器配置false拒绝跨域,havingValue属性定义了只有当name属性的值为havingValue的值时才使得@Configuration生效,这就解决了测试服允许全局跨域正式服不允许全局跨域的问题