Properties files are useful to externalize Spring Boot configuration. This post will discuss how to map all properties defined in the application.properties file to a POJO using @ConfigurationProperties.

In the previous post, we have seen how to use the @Value("${property}") annotation to inject configuration properties. If we’re working with multiple properties, this can be cumbersome. Spring Boot provides a method of working with properties that lets strongly typed beans govern and validate your application’s configuration. This post will discuss how to map all properties defined in the application.properties file to a POJO.

 
Consider the following application.properties file that contains few properties.

Config.java

The following configuration class uses @ConfigurationProperties annotation to bind and validate the class’s external configuration. Note that the annotation processor will automatically consider inner classes as nested properties.

Inject @ConfigurationProperties beans

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

 
We can also inject @ConfigurationProperties beans in the same way as any other bean, as shown in the following example:

Output:

{prod, [https://www.techiedelight.com, https://techiedelight.com],
{user1, pass1, [admin, editor, moderator]}}

That’s all about mapping Spring Boot properties to a POJO using @ConfigurationProperties.

 
Suggested Read:

Read values from the YAML file in Spring Boot