Tags: spring boot java
Spring Boot provides an elegant way to bind YAML configurations directly to Java classes using the @ConfigurationProperties annotation. This tutorial will walk you through the basics and show you how to map a nested YAML structure to a configuration class.
Consider the following YAML structure:
In this YAML:
access.projects is a list of project configurations.allowedAccess (a string) and allowedGroup (a list of strings).Ensure you have the following dependency in your pom.xml (if using Maven):
This dependency generates metadata for configuration properties, making it easier to manage properties in the IDE.
To bind the YAML structure, create a configuration class using the @ConfigurationProperties annotation.
@ConfigurationProperties("access"): Maps properties under the access key in the YAML file.Project: Represents the structure of each project entry in the projects list.@Getter and @Setter reduce boilerplate code for getters and setters.Annotate your main application class with @EnableConfigurationProperties to enable configuration property binding.
You can now inject and use the configuration in any Spring component.
For the provided YAML, the output will be:
Allowed Access: t1
Allowed Groups: [m1, m2]
Allowed Access: t2
Allowed Groups: [m2, m3]
spring-boot-configuration-processor is included for better development experience.Using @ConfigurationProperties in Spring Boot is a powerful way to manage hierarchical configurations. By following this tutorial, you can effectively bind YAML properties to Java classes and use them in your application. Happy coding!
References: