Load spring boot app properties from database - before application start

Ankit Wasankar
2 min readDec 14, 2020
Load properties from database before application start — Spring boot
Load properties from database before application start — Spring boot

Why do we even need to do that?

  • Sometimes we need to load the properties from database because they are flexible to use.
  • Sometimes we need to load database properties because we have different database property values in TEST and PROD.
  • My reason to load the properties from database because our application has UI for changing properties stored in the database and depending upon the change in properties our applications should behave after restart. For ex: If CORS is enabled through UI, then CORS configuration should be conditionally picked while restart depending upon the property value.

How to do it in Spring boot?

For those who need load properties from database before application starts, and make those props accessible by @Value anywhere in your project, just add this processor.

Eve if you copy paste the code with below database table, the code will work as is, we will go step by step through the code later.

Create database table with below columns

The create new class with below code

Understanding the code

  • Spring boot will call initialize() method automatically while stating the application but before loading the configuration classes but after loading the application properties.
  • There we checked if we have already loaded the properties or not.
  • getPropertyMapFromDatabase() this method will actually connect to database and then fetch values and put into Spring boot properties.
  • There is one extra method ViperUtils.isNotBlank() to check blank which is as follows:
public static boolean isNotBlank(Object obj) {
if (obj == null) return false;
if (obj instanceof String) {
return ((String) obj).length() > 0;
}
return true;
}

Why I used old fashioned connection & Prepared Statement?

Data source is not yet created, when the flow comes to this class. Spring boot is yet to load the configurations. So we can manually create the data-source. But then why to hassle with creating data-source when we just need just single connection to database to load the properties. If you create the data-source here you need to keep in mind that while loading configuration classes Spring should not create again.

And again while shutting down the application, Spring boot must close the data-source, even if you created from this class. Otherwise there will be stale connections to database.

So, after weighing the advantages and ease I think it’s better to make a single connection to database to load the properties and then close the connection. And then let Spring boot create data-source from configurations or auto-configurations. Spring will auto manage those connections.

Any questions or queries, let me know in comments ?

--

--