How to make Spring initialize a static variable

Jul 08

Two days ago, I faced a tricky situation while coding. Mainly I was using Spring to read database parameters into a variable so I’d never need to open the code to change database parameters. This is simply done by adding this to your applicationContext.xml file:


database-settings.properties file contains these data

database.url=url
database.username=username
database.password=password

Then whenever I need a new connection to the database I just make a variable like this

And start using it knowing that Spring filled it for me. The problem was when I made a Utility class that have only static methods, something like that:

And I needed the databaseConfig variable “taking in mind” that my class isn’t a bean and the variable must be static. After a while I figured out how to make it. All I need is to add a static setter into my class that will help Spring access my variable and inject the value into it

I didn’t even need the @Autowired annotation on my variable!

Then I added these fantastic lines into applicationContext.xml file

Now everything is working well and while Spring context is loading my variable get initialized.

7 comments

  1. Khaled Annajar /

    nice c u soon friend.

  2. Anatoly /

    Well, it’s, most likely, a proper way to initialize static fields. From my experience … I just cheated the Context factory by declaring accessor methods non-static in a static class, for example for a simple ORM (mapping database table/columns). It did work.

  3. Swati /

    I was facing same issue for last two days. It really saved me. Thanks a lot

Leave a Reply