Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we need static fields in Spring Beans?

I have seen general practice to create Logger instance as static properties of a class annotated with any of the Spring's Annotation ( @Component, @Service ).

Since, all beans created are by default singleton in nature. Do we really need static fields in this scnerio as there is only going to be once instance after all ?

like image 320
Paras Avatar asked Jan 02 '23 14:01

Paras


1 Answers

I think the same question can be asked for finals: "Why would declare a variable as final if I know I won't touch it through the code?"

Thing is, you are not the only one touching or reading the code. Giving the proper semantic meaning is essential for a readable and maintainable code. You may know that the service and/or controller will be a Singleton, so no real need to put the variables inside static, but in this way you are explicitly declaring it.

Addition:

how are you going to log something during the construction of your singleton, if construction fails :-)

I quote @dognose comment just to make the answer more complete. There is a practical problem that making the logger static addresses: logging during creation.

Follow-up:

I simply wanted to know why would we need final static Logger instead of just final Logger. What justifies a logger to be static member instead of just being class member?

Let's assume your class is not a Singleton. In this scenario, the Logger must just log. It has nothing to do with the objects, it is a class property. This means that if you instantiate one or a thousand objects, the logger does not change. So you can just share it, between all the objects, hence make it static.

Let's assume your class is a Singleton. There will be always only one instance. Is static still useful? From a practical point of view, no. You will have only one class instance, so only one logger, static or not. Still, if you declare it static, you are declaring that you want that logger to be a property of the class, not of the objects of that class. You are making your intentions and design explicit, hence improving the quality of your code.

Hope this answers your question.

like image 178
Tu.Ma. Avatar answered Jan 05 '23 14:01

Tu.Ma.