如何在属性文件中使用地图

How to use a Map in a properties file

如何在属性文件中映射它?

我正在尝试在 Spring Cloud Gateway

上关注 this documentation

然而,我们application.properties。

spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: "https://docs.spring.io"
            allowedMethods:
            - GET

我试过不同的变体都无济于事:

spring.cloud.gateway.globalcors.cors-configurations./**.allowed-origin
spring.cloud.gateway.globalcors.cors-configurations.[/**].allowed-origin

我遇到异常:

*************************** APPLICATION FAILED TO START


Description:

Failed to bind properties under 'spring.cloud.gateway.globalcors.cors-configurations.allowed-origins' to org.springframework.web.cors.CorsConfiguration:

Reason: No converter found capable of converting from type [java.lang.String] to type

[org.springframework.web.cors.CorsConfiguration]

Action:

Update your application's configuration

请注意,此代码使用的是 Spring Cloud Hoxton.M3。我知道有人可能会假设 Spring 指南中的已知实现可能是答案,但事实并非如此,因为 SC Gateway 不再使用 HttpServlet。

更新: 根据 Marcos Barbero 的说法,这是可行的。显然,Eclipse 无法将此数据类型理解为 属性。现在,您必须处理忽略解析错误的问题。

spring.cloud.gateway.globalcors.corsConfigurations.[/**].allowedOrigins=*
spring.cloud.gateway.globalcors.corsConfigurations.[/**].allowedMethods=*
spring.cloud.gateway.globalcors.corsConfigurations.[/**].allowCredentials=true

您不能使用属性文件设置这些属性。而是使用 Spring 配置来设置这些属性,如下所示:

@Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/test-javaconfig").allowedOrigins("http://localhost:9000");
            }
        };
    }

此外, post 可能会有一些帮助。

我没试过,但我想你可以这样使用它:

spring.cloud.gateway.globalcors.corsConfigurations.[/**].allowedOrigins="https://docs.spring.io"
spring.cloud.gateway.globalcors.corsConfigurations.[/**].allowedMethods[0]=GET

如果不起作用,请尝试从 [/**] 中删除方括号,导致 /**.