Software Development

Set all bean Properties with values from .properties file

This post demonstrates how to set all the bean properties with values from the .properties file using Spring Boot. We are not going to set them one at a time. We want to set them all simultaneously using the following Spring annotations.

Use Spring Initializr

For off, we’ll use Spring Initializr to generate our initial codes. You may refer to Create a Spring Boot Application using IntelliJ. For this post, you may select no dependencies in step 3.

Update pom.xml

Modify your pom.xml to include the following dependency.

Update Main class with @EnableConfigurationProperties

You have to annotate your main class.

Annotate bean with @Component and @ConfigurationProperties

Next, you have to annotate your bean.

The prefix attribute will enable Spring to pick up properties that start with that prefix value.

application.properties

The .properties contains the following properties.

Note that for property names with hyphens or dash (“-“), Spring will convert the following character to uppercase.

firstconfig.app-version is interpreted as firstconfig.appVersion.

Sample Output

Download the Codes

You may download the codes from https://github.com/Turreta/config2pojo

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like