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.

3

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.