我有一个 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"));
}