I would like to read the array in the YAML file in java spring. I don't know if it's possible to use an array of objects. Here is the content of the YAML:
main:
nodes:
-
label: "My label"
id: "My label id"
uri: ""
-
label: "My label"
id: "My label id"
uri: ""
And here is my component which loads the file:
public class MyNode {
String label, id, uri;
}
@ConfigurationProperties(prefix = "main")
@PropertySource(value = "classpath:mycustomfile.yml", factory = YamlPropertyLoaderFactory.class)
@Component
public class CustomProperties {
private List<MyNode> nodes;
}
And the YamlPropertySourceFactory
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource)
throws IOException {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(encodedResource.getResource());
Properties properties = factory.getObject();
return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
}
}
When I run my application, nodes are null. I followed Baeldun tutorial
CodePudding user response:
It seems that the problem comes from the visibility of your MyNode class members. If you define public setters for all the members, everything will work fine. So just try to modify
public class MyNode {
String label, id, uri;
}
to
public class MyNode {
private String label, id, uri;
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
}
CodePudding user response:
I solved it by adding @Data (Lombok) and make MyNode as inner static class. You can also add getter and setter if you don't use Lombok.
@ConfigurationProperties(prefix = "main")
@PropertySource(value = "classpath:mycustomfile.yml", factory = YamlPropertyLoaderFactory.class)
@Component
public class CustomProperties {
private List<MyNode> nodes;
@Data
public static class MyNode {
private String label, id, uri;
}
}