问题
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
}
}
}
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?
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"));
}
回答1:
I would try with the NESTED_NESTEDPROPS_PROP, bcs 'nestedProps' is one property
The _ delimiter must not be used within a property name. i.e. database-platform must be written as DATABASEPLATFORM and not DATABASE_PLATFORM.
source: https://github.com/spring-projects/spring-boot/wiki/Relaxed-Binding-2.0
来源:https://stackoverflow.com/questions/31729516/spring-boot-camel-case-nested-property-as-environment-variable