Spring boot 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
由于我的AddressProperties
对象为null
,因此无法正确绑定。
当一个类与yml属性AddressProperties
同名时 - > Address
它运作良好。我尝试使用前缀Qualifier
添加ConfigurationProperties
或address
,但它无效。不幸的是,我在spring docs中找不到有关此案例的有用信息。
如何为嵌套属性指定前缀?
答案 0 :(得分:2)
yaml / property文件中定义的属性应该与类中定义的变量匹配。 将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
。
答案 1 :(得分:0)
您可以简单地取消嵌套这两个类,使每个类都有自己的前缀。 头等舱:
@Configuration
@ConfigurationProperties(prefix="person")
public class PersonProperties {
private AddressProperties addressProperties;
public AddressProperties getAddressProperties() {
return addressProperties;
}
public void setAddressProperties(final AddressProperties addressProperties) {
this.addressProperties = addressProperties;
}
}
第二堂课
@Configuration
@ConfigurationProperties(prefix="person.address")
public class PersonAddressProperties {
private String line1;
public String getLine1() {
return line1;
}
public void setLine1(final String line1) {
this.line1 = line1;
}
}
编辑:如注释中所指出,如果需要一个代码块来引用两组属性,则必须注入这两个类。