Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which happens first--Dependency Injection from Spring, or the execution of a static block?

I have a class that uses a static block to initialize a static Hashtable. This is done by reading a properties file, parsing the contents of the file, and then setting the appropriate values into the Hashtable.

However, instead of specifying the location of the file, I would like to inject the location instead using Spring, basically to eliminate any hard-coded values in the class. I did see somewhere else that it is in fact possible to inject into a static variable, but that it will involve the use of a non-static setter.

So my question is--will the invocation of the setter happen before the static block is executed, or will the static block execute first before Spring invokes the setter (which will basically cause an exception in my code)?

Thank you!

like image 400
cdegu Avatar asked Oct 07 '22 22:10

cdegu


1 Answers

The static initializer is executed by the classloader as part of loading the class before any code is granted access to the class. Since Spring must instantiate the class--which definitely requires loading the class--before it can call setters on that instance, the static initializer block has already run.

like image 121
David Harkness Avatar answered Oct 10 '22 02:10

David Harkness