Roh*_*her 9 java spring spring-boot java-record java-17
如何将application.yaml具有嵌套属性的配置映射到 Java 中的类似记录结构?
例如,如果我们有以下 yaml:
foo:
bar:
something: 42
baz:
otherThing: true
color: blue
Run Code Online (Sandbox Code Playgroud)
所需的记录结构将类似于:
@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
) {}
Run Code Online (Sandbox Code Playgroud)
我认为为了简单起见,您可以使用以下命令创建一个文件:
@ConfigurationProperties(prefix = "foo")
public record Foo(Bar bar) {
public record Bar(Baz baz) {
public record Baz(String bum) {}
}
}
Run Code Online (Sandbox Code Playgroud)
这在 spring-boot 中工作得很好,你不需要重复注释,使用它时你只需使用:
String bumVal = foo.bar().baz().bum();
Run Code Online (Sandbox Code Playgroud)
其中 foo 只是注入到您需要的 Bean 中。
我什至删除了@ConsructorBindingas 自 spring-boot 2.6 起,只要记录仅定义一个构造函数,就不再需要它了,请参阅发行说明。
上面的配置与你自己的答案结构有关,但这也是原始问题结构的紧凑方式:
@ConfigurationProperties(prefix = "foo")
public record Foo(Bar bar, Baz baz, String color) {
public record Bar(String something) {
}
public record Baz(String otherThing) {
}
}
Run Code Online (Sandbox Code Playgroud)
我发现该record类型对于这个用例非常有用,因为它非常紧凑,不需要编写太多代码。
小智 4
您不需要@ConfigurationProperties每个嵌套类。它仅适用于根类(Foo.class)。然后通过将 Foo 插入@Component类上方或放在@ConfigurationPropertiesScanApplication 类上,将 Foo 作为 Spring Bean。