Issue
Spring will automatically bind properties defined in application.properties
or application.yml
to fields defined in @ConfigurationProperties
-annotated classes. For instance, in my application.properties
I can have:
fizz.buzz=35
fizz.foo=hello
And in my Java code I can have:
@ConfigurationProperties("fizz")
public class FizzProperties {
private Integer buzz;
private String foo;
// ...
}
And at runtime FizzProperties#buzz
will get a value of 35
injected into it and FizzProperties#foo
will have a value of "hello"
injected into it.
I'm wondering what the naming convention is for camel-cased Java fields, and also for hyphens ("-"
) and periods ("."
) used in the properties files. For instance, if I had:
fizz.whistle-feather=true
fizz.baz.boo=always
What would their corresponding Java fields need to look like in order for Spring to map and inject them properly?
public class Baz {
private String boo;
}
@ConfigurationProperties("fizz")
public class FizzProperties {
private Integer whistleFeather; // correct?
private Baz baz; // correct?
// ...
}
Are my assumptions correct here or misled (and if misled, how so)? I can't find this explained in the Spring docs.
Solution
As stated in spring-boot docs, it uses "relaxed binding", so both properties "whistle-feather" and "whistleFeather" will be mapped to your private Integer whistleFeather
, but it's recommended, when possible, to store properties in lower-case kebab format, such as fizz.whistle-feather=10
.
So your first case is correct.
The second case is also correct, because dots are used as delimiters in application.properties
, while YAML file uses as delimiters both dots and colon.
You also may define nested properties as nested classes to store them in one place like this:
@ConfigurationProperties("fizz")
public class FizzProperties {
private Integer whistleFeather;
private Baz baz;
// getters, setters
public static class Baz {
private String boo;
// getters, setters
}
}
Take a look here for more info about spring-boot properties binding and examples.
Answered By - AndrewThomas
Answer Checked By - David Goodson (JavaFixing Volunteer)