【发布时间】: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