gpt4 book ai didi

java - spring中嵌套配置属性的前缀

转载 作者:行者123 更新时间:2023-11-30 02:10:12 27 4
gpt4 key购买 nike

Spring 启动 2.0.0.RELEASE

我有属性类:

@Configuration
@ConfigurationProperties(prefix="person")
public class PersonProperties {

private AddressProperties addressProperties;

public AddressProperties getAddressProperties() {
return addressProperties;
}

public void setAddressProperties(final AddressProperties addressProperties) {
this.addressProperties = addressProperties;
}

public static class AddressProperties {

private String line1;

public String getLine1() {
return line1;
}

public void setLine1(final String line1) {
this.line1 = line1;
}
}

}

application.yml:

person:
address:
line1: line1OfAddress

它没有正确绑定(bind),因为我的 AddressProperties 对象是 null。当类与 yml 属性 AddressProperties -> Address 具有相同名称时,它可以正常工作。我尝试添加带有前缀 addressQualifierConfigurationProperties 但它不起作用。不幸的是,我在 spring 文档中找不到有关此案例的有用信息。

如何为嵌套属性指定前缀?

最佳答案

yaml/属性文件中定义的属性应与类中定义的变量匹配。将 yaml 文件更改为

person:
# addressProperties will also work here
address-properties:
line1: line1OfAddress

或者将你的bean定义为

@Configuration
@ConfigurationProperties(prefix = "person")
public class PersonProperties {

// here variable name doesn't matter, it can be addressProperties as well
// setter / getter should match with properties in yaml
// i.e. getAddress() and setAddress()
private AddressProperties address;

public AddressProperties getAddress() {
return address;
}

public void setAddress(AddressProperties address) {
this.address = address;
}
}

如果您想获取地址下的所有属性而不在单独的 bean 中定义它们,您可以将 PersonProperties 类定义为

@Configuration
@ConfigurationProperties(prefix = "person")
public class PersonProperties {

private Map<String, Object> address;

public Map<String, Object> getAddress() {
return address;
}

public void setAddress(Map<String, Object> address) {
this.address = address;
}
}

这里PersonProperties#address将包含{line1=line1OfAddress}

现在,地址下的所有属性都将位于 map 中。

关于java - spring中嵌套配置属性的前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50345888/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com