Issue
How can one map an application.yaml
configuration with nested properties to a similar record structure in Java?
E.g., if we have the following yaml:
foo:
bar:
something: 42
baz:
otherThing: true
color: blue
The desired record structure would be something along the lines of:
@ConfigurationProperties(prefix = "foo")
@ConstructorBinding
public record Foo(
Bar bar,
Baz baz,
String color
) {}
// ---
@ConfigurationProperties(prefix = "foo.bar")
@ConstructorBinding
public record Bar(
int something
) {}
// ---
@ConfigurationProperties(prefix = "foo.baz")
@ConstructorBinding
public record Baz(
boolean otherThing
) {}
Solution
You don't need @ConfigurationProperties
for each nested class. It only for the root class (Foo.class). Then make the Foo as Spring Bean by inserting @Component
above the class or put @ConfigurationPropertiesScan
on the Application class.
Answered By - Ferry
Answer Checked By - David Marino (JavaFixing Volunteer)