简体   繁体   中英

Is it possible to user a YAML sequence with Spring Boot configuration properties?

I have a requirement for a Spring Boot application to load some configuration that would ideally be suited to a sort of mini-spreadsheet. Almost all the configuration consists of YAML properties files that are bound to @ConfigurationProperties POJOs thus:

static class Entry {
    private final Terrain terrain;    // A simple enumeration
    private final int value;
    // ... other fields

    public Entry(Terrain terrain, int value, ...) { ... }
}

@ConfigurationProperties("section")
@ConstructorBinding
@Validated
class SectionProperties {
    private final List<Entry> entries;

    public SectionProperties(List<Entry> entries) {
        this.entries=  List.copyOf(entries);
    }

    // ... other fields, getters, etc
}

This works fine if the YAML is structured as a sequence of objects like this:

section:
  entries:
    - terrain: plains
      value: 1
    - terrain: forest
      value: 2

However it would great from the perspective of the user/author of this configuration if the data was organised as a 'spreadsheet' as they would then be able to see the various values in context of each other, rather than the big list above (there are around a dozen or so entries). Something like this:

section:
  entries:
    - [plains, 1]
    - [forest, 2]

This is valid YAML (as far as I can tell) but the configuration binding fails dismally with the 'unbound properties' error for every entry in the list, ie it seems to recognise entries as a YAML sequence but cannot bind the data within the YAML sequence block (the square brackets) to an Entry .

Has anyone attempted to do this or anything similar? Is it possible?

Apologies if this has already been addressed elsewhere, I've searched SO and the Spring documentation but cannot find anything that covers this specific case and whether its actually feasible.

This should be possible if you implement the mapping yourself:

@Component
@ConfigurationPropertiesBinding
public class EntryConverter implements Converter<List<String>, Entry> {
    @Autowired
    private ConversionService conversionService;

    @Override
    public Entry convert(List<String> from) {
        String[] data = from.split(",");
        return new Entry(data[0],
                conversionService.convert(data[1], Integer.class), ...);
    }
}

I am unsure whether that would work non-scalar values nested in the list an I am also unsure whether it works for List<Entry> . Give it a try and report back:).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM