简体   繁体   中英

How can I use @Value or autowire Environment in a class with private constructor?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM