2

I have a use case where I am using a utility class (class which contains methods that are all static and the constructor is also private). Therefore, I am not creating the object of the class, I am just accessing the methods with the class name. So, in the utility class I want to access the application.properties. But neither @Value nor autowiring Environment works. It always returns null.

Is there a way to access fields in application.properties in a utility class? I searched for it a lot, but I didn’t find any references.

Trayambak
  • 55
  • 1
  • 6
  • Does this work for you? https://stackoverflow.com/a/63334369/5050667 – Yassin Hajaj Apr 11 '21 at 09:38
  • Does this answer your question? [Can you use @Autowired with static fields?](https://stackoverflow.com/questions/1018797/can-you-use-autowired-with-static-fields) – Jahan Zinedine Apr 11 '21 at 09:39
  • Hi HANS, welcome to Stackoverflow! When asking questions, it's helpful to have a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) to best assist with helping your question. – Richard Kenneth Niescior Apr 11 '21 at 10:29

1 Answers1

4

That's the problem with static classes and fields. Their creation is not in the hands of the Spring or any other dependency injection framework. Thus, Dependency injection frameworks can't inject any value into it.

You can access beanManager and read the value or post initialize your values when spring boot is initialized. Still, your value is null while the Spring boot initialization process is in progress.

Better yet define a Singleton bean using Spring @Scope("singleton"). Change your class to a normal one and let its lifecycle and creation be managed by Spring, you will make it easier to test cuz testing static classes is not always easy.

Jahan Zinedine
  • 14,616
  • 5
  • 46
  • 70