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.

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.

Add a Comment

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