JuHarm89
JuHarm89

Reputation: 877

Spring Boot @ConfigurationProperties YAML referencing

I really like the @ConfigurationProperties-functionality of Spring to load my configuration properties via YAML into a Java class.

Normally I would use it in a way, that I have the following yaml-file:

lst:
  typ:
    A: "FLT"
    B: "123"
    C: "345"
    D: "TTS"

The type-attribute would be mapped to a Java-Map. Now i would like to have a solution to reference yaml-fragments in the yaml-file itself, so that I could reuse the reference to the fragment:

lst: ${typs}

typs:
  A: "FLT"
  B: "123"
  C: "345"
  D: "TTS" 

Is that possible with Spring and @ConfigurationProperties?

Upvotes: 1

Views: 2349

Answers (1)

alexbt
alexbt

Reputation: 17045

I believe it is only possible to use placeholder with string properties. This leaves you with 2 options:

Solution - Define the map as a comma-separated String of key-values

The whole explanation is provided if you click on the link above. I'll walk you through it.

(1) application.yml:

prop1: A:FLT, B:123, C...
prop2: ${prop1}

(2) Define a String to Map converter/splitter (from @FedericoPeraltaSchaffner's answer)

@Component("PropertySplitter")
public class PropertySplitter {
    public Map<String, String> map(String property) {
        return this.map(property, ",");
    }
    private Map<String, String> map(String property, String splitter) {
        return Splitter.on(splitter).omitEmptyStrings().trimResults().withKeyValueSeparator(":").split(property);
    }
}

(3) Inject the map using @Value and the splitter:

@Value("#{PropertySplitter.map('${prop1}')}")
Map<String, String> prop1;

@Value("#{PropertySplitter.map('${prop2}')}")
Map<String, String> prop2;

Upvotes: 2

Related Questions