In this quick tutorial, we’ll learn how to use a YAML file to configure properties of a Spring Boot application.
Instead of having an application.properties in Spring, we can use the application.yml as our configuration file. YAML is a superset of JSON and we can use it for configuring data. The YAML files are more human-readable, especially when we have a lot of hierarchical configurations in place.
Let’s see what a very basic YAML file looks like:
server: url: http://localhost myapp: name: MyApplication threadCount: 4 ...
server.url=http://localhost server.myapp.name=MyApplication server.myapp.threadCount=4 ...
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>2.1.5.RELEASE</version> </dependency>
We can use the spring.profiles key to mention the profile for which a property value applies. For example:
spring: profiles: dev | test server: url: http://localhost app: name: MyApplication threadCount: 4 users: - A - B ---- spring: profiles: prod server: url: http://myapp.org app: name: MyApplication threadCount: 10 users: - Jacob - James
-Dspring.profiles.active=dev
One way to access YAML properties is to use the @Value(“${property}”) annotation. However, there’s another popular method that ensures that the strongly typed beans govern and validate our app configuration.
To implement that, we’ll create a @ConfigurationProperties class which maps a set of related properties:
@ConfigurationProperties("server") public class ServerProperties { private String url; private final App app = new App(); public App getApp() { return app; } //getter and setter for url public static class App { private String name; private String threadCount; private List<String> users = new ArrayList<>(); //getters and setters } }
Let’s now define our AppConfig class:
@Configuration @EnableConfigurationProperties(ServerProperties.class) public class ApplicationConfig { ... }
We can now access the YAML properties by making use of the @ConfigurationProperties beans that we have created. We’ll inject these property beans just like any regular Spring bean:
@Service public class AppService { @Autowired private ServerProperties config; public void printConfigs() { System.out.println(this.config.getUrl()); System.out.println(this.config.getApp().getName()); System.out.println(this.config.getApp().getThreadCount()); System.out.println(this.config.getApp().getUsers()); } }
In this tutorial, we learned how to use YAML configuration files in Spring Boot application.