Java, Software Development, Spring, Spring Boot

Read From Multiple Properties Files In Spring Boot

In most cases, our applications do not use a single properties file. Why? One, we do not want to have a huge configuration file. Second, modular configuration – we can just swap out parts of the configuration and swap in with another. This awesome post shows how to read properties from multiple properties files in Spring Boot and it will help you sleep like a baby tonight!

Requirements

We use the following.

  1. Java 8
  2. Spring Boot 1.5.8.RELEASE
  3. Spring Initialzr
  4. IntelliJ IDEA or Eclipse

Multiple Properties Use Case

If we want to read multiple properties files, then we need more than one properties file. For this post, we have application.properties , config001.properties , and config002.properties .

application.properties

This file has this content.

config001.properties

While this has the following.

config002.properties

This file contains the following.

For simplicity, we place these files in the resources directory in the Maven project.

Read from multiple properties files in Spring Boot

A Singleton in Spring Boot

We use a singleton bean whose properties map to entries in 3 separate properties files. This is the main class to read properties from multiple properties files into an object in Spring Boot.

We use @PropertySource and locations of the files in the classpath. The application.properties is not used because it is implicitly included in the PropertySource by Spring Boot. Alternatively, we could use PropertySourced.

Multiple Properties Demo and Test

We have a main class that displays the values from the bean.

This outputs the following.

The codes are available here.

Loading

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