You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Spring Cloud Gateway获取CORS允许源值及@Value配置方法

问题解答

1. 从Spring Cloud Gateway中获取CORS允许源(allowedOrigins)的值

常用的获取方式有三种:

  • 通过Environment直接读取:注入Environment对象,调用getProperty方法传入完整配置路径,适合快速获取单个配置项。
  • 使用@ConfigurationProperties绑定:创建配置类绑定整个globalcors配置结构,适合需要批量读取或复用配置的场景。
  • 从Gateway的CORS配置实例中提取:若Gateway已完成初始化,可通过CorsConfigurationSource或相关Bean获取加载后的CorsConfiguration对象,直接从中取出allowedOrigins集合。

2. 使用@Value读取指定YAML配置项

你的YAML中cors-configurations下的键是'[/**]',属于特殊字符组成的键,在@Value中需要对特殊部分做处理,以下两种写法都可行:

方式一:用单引号包裹特殊键

@Value("${spring.cloud.gateway.globalcors.cors-configurations.'[/**]'.allowedOrigins}")
private String allowedOrigins;

方式二:通过SpEL表达式读取

@Value("#{environment.getProperty('spring.cloud.gateway.globalcors.cors-configurations.[/**].allowedOrigins')}")
private String allowedOrigins;

注意:如果配置的是多个允许源(逗号分隔),读取到的会是逗号拼接的字符串,需要自行拆分转为集合。


内容的提问来源于stack exchange,提问作者Archimedes Trajano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 15:30:58