Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Spring boot yaml configuration list property via environment variables

I am configuring my Spring Boot application with an application.yml file:

foo:
  bar: foobar
foolist:
- bar: foobar1
  baz: foobaz1
- bar: foobar1
  baz: foobaz1

I can easily set the foo.bar value with an environment variable, e.g.

export FOO_BAR=value

How can I set values of the foolist entrie? FOOLIST[0]_BAR is not a valid identifier and FOOLIST_0_BAR does not work.

like image 897
feob Avatar asked Jan 30 '17 15:01

feob


People also ask

How do I set 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 can we read properties file in Spring Boot using environment?

Read properties Using the Environment Object One of the easiest ways to read a property from the application. properties file is by autowiring an Environment object. All you need to do is to use the @Autowired annotation. It is called dependency injection.

How can we access the YAML properties in Spring Boot?

To access the YAML properties, we'll create an object of the YAMLConfig class, and access the properties using that object. In the properties file, we'll set the spring. profiles. active environment variable to prod.

Which is a better way to configure a Spring Boot project using properties or YAML?

yml file is advantageous over . properties file as it has type safety, hierarchy and supports list but if you are using spring, spring has a number of conventions as well as type conversions that allow you to get effectively all of these same features that YAML provides for you.


1 Answers

It's possible to provide arbitrary JSON object in the SPRING_APPLICATION_JSON environment variable:

export SPRING_APPLICATION_JSON='{"foolist":[{"bar": "foobar1", "baz: foobaz1"}, {"bar": "foobar2", "baz: foobaz2"}]}'

Documentation is here: https://docs.spring.io/spring-boot/docs/1.4.x/reference/html/boot-features-external-config.html

like image 175
Slava Semushin Avatar answered Sep 29 '22 08:09

Slava Semushin