Updating Spring Component Properties at Runtime

This is the third and final post covering a new SiteOptions Component in our NixMash Spring app. We first covered the logic in retrieving Key-Value pairs from a datasource and populating the SiteOptions Class Properties with Apache PropertyUtils and Reflection. We then went through the process of moving that logic into a Spring Component using @PostConstruct and @DependsOn Interfaces to populate our Component on Initialization.

Today we’ll address how to update those Component Properties at Runtime. Our SiteOptions Component will house data like Site Name, Google Analytics TrackingID, and other options we’ll want to update in our Administration Area and have those changes applied immediately.

The Question: How are we going to update our Spring Component? It’s a Bean that is loaded into our Spring Application Context, so do we 1) Reload the Bean in the Context, or 2) Reload the Context to reflect the new changes in our SiteOptions Class Properties?

The Answer: Both of those options are the wrong way of looking at updating our properties. Our SiteOptions Component is in Application Context, yes, a Singleton Bean which interacts with other Beans, so we keep it there, retain Context, and merely update its properties when needed!

We’ll start in our Service Method where we pass a SiteOptionsDTO Container with our updated Key-Value pair. We send it to our datasource Repository for Update in found.update(…). Now we’re at the place where our question on how to update the Component is answered. In our try-catch{} block we call the SiteOptions setSiteOptionsProperty() method to update our In-Context Bean Properties.

We covered the setSiteOptionProperty() method before, but we’ll look at it again to complete our update process.

Testing the Runtime Component Updates

Let’s look at the tests to confirm that the Component Properties were updated at runtime. We confirm our original property values, update the SiteOption Key-Values through our SiteService Component, then confirm our In-Context SiteOptions Component Properties reflect the new values.

Source Code Notes for this Post

All source code discussed in this post can be found in my NixMash Spring GitHub repo and viewed online here.