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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With