This post will discuss how to read values defined in the application.yml file in a Spring Boot application.

In a Spring Boot application, we can use properties files, YAML files, environment variables, and command-line arguments to externalize our configuration. This is useful while working with the same application code in different environments. This post will discuss how to read values defined in the application.yml file.

application.yml

Following is a simple YAML file containing demo.environment and demo.hosts properties. The demo.environment is a string type, and demo.hosts is a collection of String.

 
Spring Boot provides a method of working with properties that lets strongly typed beans govern and validate the configuration of your application, as shown in the following example:

Config.java

The Following configuration class uses @ConfigurationProperties annotation to bind and validate the external configuration to this class.

Main.java

Now that all properties are loaded from a YAML file, we create an object of the Config class and display the properties using the CommandLineRunner.

Output:

{prod, [https://www.example1.com, https://www.example2.com]}

That’s all about reading values from the YAML file in Spring Boot.