【问题标题】:spring-boot camel case nested property as environment variablespring-boot骆驼案例嵌套属性作为环境变量
【发布时间】:2015-10-22 03:35:39
【问题描述】:

我有一个 Spring Boot 应用程序,并希望通过环境变量在一个用 @ConfigurationProperties 注释的类中设置一个二级嵌套属性,即驼峰式。这是该类的一个示例:

@SpringBootApplication
@EnableConfigurationProperties(SpringApp.Props.class)
@RestController
public class SpringApp {

  private Props props;

  @ConfigurationProperties("app")
  public static class Props {
    private String prop;
    private Props nestedProps;

    public String getProp() {
      return prop;
    }

    public void setProp(String prop) {
      this.prop = prop;
    }

    public Props getNestedProps() {
      return nestedProps;
    }

    public void setNestedProps(Props nestedProps) {
      this.nestedProps = nestedProps;
    }

  }

  @Autowired
  public void setProps(Props props) {
    this.props = props;
  }

  public static void main(String[] args) {
    SpringApplication.run(SpringApp.class, args);
  }

  @RequestMapping("/")
  Props getProps() {
    return props;
  }

}

当我尝试使用以下环境变量运行应用程序时:

APP_PROP=val1
APP_NESTED_PROPS_PROP=val2
APP_NESTED_PROPS_NESTED_PROPS_PROP=val3

我收到了来自服务的以下响应:

{
  "prop": "val1",
  "nestedProps": {
    "prop": "val2",
    "nestedProps": null
  }
}

这是预期的行为吗?我期待这样的事情:

{
  "prop": "val1",
  "nestedProps": {
    "prop": "val2",
    "nestedProps": {
      "prop": "val3",
      "nestedProps": null
    }
  }
}

当我通过应用程序参数设置属性时(例如:--app.prop=val1 --app.nestedProps.prop=val2 --app.nestedProps.nestedProps.prop=val3),我得到了预期的响应。

是否有任何使用环境变量且不修改代码以获得预期行为的解决方法?

注意:我做了一些调试,似乎问题出在org.springframework.boot.bind.RelaxedNames 没有为这种情况生成候选者。这是我为证明它所做的测试(它失败了):

@Test
public void shouldGenerateRelaxedNameForCamelCaseNestedPropertyFromEnvironmentVariableName() {
  assertThat(new RelaxedNames("NESTED_NESTED_PROPS_PROP"), hasItem("nested.nestedProps.prop"));
}

【问题讨论】:

    标签: java spring-boot environment-variables


    【解决方案1】:

    我会尝试使用 NESTED_NESTEDPROPS_PROP,bcs 'nestedProps' 是一个属性

    属性名称中不得使用 _ 分隔符。 IE。 database-platform 必须写为 DATABASEPLATFORM 而不是 DATABASE_PLATFORM。

    来源:https://github.com/spring-projects/spring-boot/wiki/Relaxed-Binding-2.0

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      • 2016-07-27
      • 2017-09-03
      • 2022-01-12
      • 2014-09-14
      • 1970-01-01
      • 2021-02-09
      相关资源
      最近更新 更多