How to Load Application Properties from Database

Every Java application whether its simple standalone or multi aspect complex enterprise java web application it will rely on some static properties file. This property file goes through constant changes by the hands of developers, deployment and configuration managers. Everyone changes the values in properties file as per their environment. We even end up keeping multiple properties file in our project. Each file will have environment specific values for example development, staging, quality, acceptance, pre-production and production.

Once code is moved to higher environment where application is deployed through some managed process, any change in the properties file has to be checked in to scm tools and then deployed to the targeted environment. In this article we will see the utility that will load the application properties from database. Any change in the property needs only application restart and you will get updated values from database.

Software used in this example

  • Java 8
  • MySQL
  • Eclipse

We will first define our data source as below

Once that is done, we will define our table that will hold key and value pairs for our application configuration

Post this we will define our custom property processor class that will extend Spring’s PropertyPlaceholderConfigurer and will load properties from database

Above class is configured as bean and it is supplied the datasource of our application. You can also note that we have set localOverride as true. This will make sure that properties from database take precedence over that available in any properties file.

And here is our custom properties class

This will make sure that you will have properties loaded from database as well as any additional configuration that you can safely put in application. You can access these properties directly using @Value annotation or you can call utility method provided along with the above class. We will see now our sample properties file and its output using test controller

Sample Controller

And below is the output of our rest point http://localhost:8080/getval?key=con.key1

We have properties value set from out database. Hope above code sample will be helpful to someone.

If you need to refer to the AppUtil class to run this application properties from database example, you can look in to one present in our Git Repo – AppUtil.java

 

9 Comments
  1. Dharm
    July 20, 2019 | Reply
    • Pavan
      July 22, 2019 | Reply
  2. Chetna
    December 15, 2017 | Reply
    • Chetna
      December 29, 2017 | Reply
  3. Pinaki
    November 15, 2017 | Reply
  4. Lakshman M
    May 5, 2017 | Reply
    • Pavan
      May 6, 2017 | Reply
  5. Ankur Mukherjee
    April 19, 2017 | Reply
    • Pavan
      April 19, 2017 | Reply

Add a Comment

Your email address will not be published. Required fields are marked *