Using @PostConstruct and @DependsOn in Spring

We began discussing a new Spring SiteOptions component which will house various properties for our NixMash Spring web application. We would store the SiteOptions class properties in a database rather than in a properties file. The property values would be Booleans, Integers and Strings, so different Types loaded dynamically.

In our last post we covered the logic of retrieving the Key-Value pairs from a database, converting them to a HashMap<String, Object>(), then using Apache Commons Bean Utilities and Reflection to populate the property values.

Today we’ll begin moving that logic out of our @Test code and into our working Spring App. Our approach will be to add a @PostConstruct method to our SiteOptions Properties Class which executes after the Bean is injected. That allows us to create our SiteOptions Bean and populate it on app startup.

If all works according to plan, we should be able to fire up our Spring Boot app, load a bean which autowires SiteOptions and we’re good to go.

Yes!

We have two Profiles, MYSQL and H2. Our MYSQL profile used above is working great, but H2 is spitting out NULLS!

We’ll look at our @PostConstruct method now. Notice we’re retrieving the initial Key-Value data from a database using our siteOptionRepository, so we need that Bean fully initialized and operational to do the job. Something’s going on in our database process, however, because the siteOptionKeyValues Collection retrieves MYSQL data but is empty when using H2.

No H2 data, but why? H2 configuration loads a SQL script on startup, which MySQL doesn’t, so let’s go to the H2Config class where the H2 data script is initialized, or more specifically, the databasePopulator Bean.

Enter @DependsOn

@DependsOn to the rescue, because we’re going to make sure the databasePopulator Bean is initialized and the H2 data entry script executes before we load the Key-Value data in the SiteOptions Init() method.

That does it! Our SiteOptions Class Properties are fully populated and ready-to-rock on app startup with H2.

There is one interesting addition we need to make, however. H2 Profile is working, but now MYSQL is not. We’re getting an Exception telling us there is no “databasePopulator” bean in our MYSQL Profile. Adding one to the MySqlConfig class is the fix.

Now that we’ve got our fully populated SiteOptions Component on App Startup, we’ll see what happens when we want to make changes to those property values at run-time. Stay tuned!

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.