问题描述
我有一个spring boot应用程序,并且希望通过环境变量在一个以@ConfigurationProperties
注释的类中设置一个第二层嵌套属性,即驼峰式.这是该类的示例:
I have a spring boot application and want to set, though environment variables, in a class annotated with @ConfigurationProperties
a second level nested property which is camel case. Here is an example of the class:
@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;
}
}
当我尝试使用以下环境变量运行应用程序时:
when I try to run the application with following environment variables:
APP_PROP=val1
APP_NESTED_PROPS_PROP=val2
APP_NESTED_PROPS_NESTED_PROPS_PROP=val3
我从服务中得到以下回应:
I'm getting following response from the service:
{
"prop": "val1",
"nestedProps": {
"prop": "val2",
"nestedProps": null
}
}
这是预期的行为吗?我期待这样的事情:
Is this the expected behavior? I was expecting something like this:
{
"prop": "val1",
"nestedProps": {
"prop": "val2",
"nestedProps": {
"prop": "val3",
"nestedProps": null
}
}
}
当我通过应用程序参数(例如:--app.prop=val1 --app.nestedProps.prop=val2 --app.nestedProps.nestedProps.prop=val3
)设置属性时,得到了预期的响应.
When I am setting the properties through application parameters (eg: --app.prop=val1 --app.nestedProps.prop=val2 --app.nestedProps.nestedProps.prop=val3
), I'm getting expected response.
是否有使用环境变量且无需修改代码即可获得预期行为的解决方法?
Is there any workaround using environment variables and without modifying the code to get the expected behavior?
注意:我进行了一些调试,似乎问题出在org.springframework.boot.bind.RelaxedNames
上,而不是针对这种情况生成候选对象.这是我为证明它的测试(失败):
Note: I did some debugging and seems the problem is originated in org.springframework.boot.bind.RelaxedNames
not generating candidates for this cases. Here is a test I did to demonstrate it (it fails):
@Test
public void shouldGenerateRelaxedNameForCamelCaseNestedPropertyFromEnvironmentVariableName() {
assertThat(new RelaxedNames("NESTED_NESTED_PROPS_PROP"), hasItem("nested.nestedProps.prop"));
}
推荐答案
我会尝试使用NESTED_NESTEDPROPS_PROP,bcs'nestedProps'是一个属性
I would try with the NESTED_NESTEDPROPS_PROP, bcs 'nestedProps' is one property
来源: https://github.com/spring -projects/spring-boot/wiki/Relaxed-Binding-2.0
这篇关于spring-boot骆驼案例嵌套属性作为环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!