Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring application.yml reference list from another property

I have property file application-dev.yml with content:

spring.profiles: dev
config.some.value:
- ELEMENT1
- ELEMENT2

and another application-staging.yml with content:

spring.profiles: staging
config.some.value:
- ELEMENT1
- ELEMENT2
- ELEMENT3

so I basically do not know size of list. When I reference this list in main application.yml like this:

some.value: ${config.some.value}

I get Failed to convert property value of type 'java.lang.String' to required type 'java.util.List' for property 'value'. How to reference it correctly?

like image 813
Mateusz Avatar asked Jan 25 '19 13:01

Mateusz


People also ask

How do I load environment specific properties in spring boot?

Environment-Specific Properties File. If we need to target different environments, there's a built-in mechanism for that in Boot. We can simply define an application-environment. properties file in the src/main/resources directory, and then set a Spring profile with the same environment name.

How do I apply different application properties in spring boot?

So in a spring boot application, application. properties file is used to write the application-related property into that file. This file contains the different configuration which is required to run the application in a different environment, and each environment will have a different property defined by it.

Can we use both YAML and properties in spring boot?

As well as Java properties files, we can also use YAML-based configuration files in our Spring Boot application. YAML is a convenient format for specifying hierarchical configuration data.


1 Answers

Solution

One way would be to use comma-separated lists in your profiles:

  • application-dev.yml
spring.profiles: dev
config.some.value: ELEMENT1,ELEMENT2
  • application-staging.yml
spring.profiles: staging
config.some.value: ELEMENT1,ELEMENT2,ELEMENT3

Then you should be able to access it in application.yml

some.value: ${config.some.value}

This solution doesn't require knowing list size upfront.

Explanation

The reason why this is working is described here. Specifically:

YAML lists are represented as comma-separated values (useful for simple String values) and also as property keys with [index] dereferencers, for example this YAML:
servers:
    - dev.bar.com
    - foo.bar.com
Would be transformed into these properties:
servers=dev.bar.com,foo.bar.com
servers[0]=dev.bar.com
servers[1]=foo.bar.com

In particular this means, that if you specify comma-separated list of strings in application.yml and define List<String> as value in @ConfigurationProperties, spring configuration properties binder will convert that comma-separated list of string to List<Strings>.

like image 113
Oleksii Zghurskyi Avatar answered Oct 25 '22 21:10

Oleksii Zghurskyi