简体   繁体   English

如何在具有私有构造函数的 class 中使用 @Value 或 autowire 环境?

[英]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).我有一个用例,我正在使用实用程序 class(包含所有 static 的方法的类,并且构造函数也是私有的)。 Therefore, I am not creating the object of the class, I am just accessing the methods with the class name.因此,我没有创建 class 的 object,我只是使用 class 名称访问方法。 So, in the utility class I want to access the application.properties .因此,在实用程序 class 中,我想访问application.properties But neither @Value nor autowiring Environment works.但是@Value和自动装配Environment都不起作用。 It always returns null .它总是返回null

Is there a way to access fields in application.properties in a utility class?有没有办法访问实用程序 class 中的application.properties中的字段? I searched for it a lot, but I didn't find any references.我搜索了很多,但我没有找到任何参考资料。

That's the problem with static classes and fields.这就是 static 类和字段的问题。 Their creation is not in the hands of the Spring or any other dependency injection framework.它们的创建不在 Spring 或任何其他依赖注入框架的手中。 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.当 spring 启动初始化时,您可以访问 beanManager 并读取值或初始化您的值。 Still, your value is null while the Spring boot initialization process is in progress.尽管如此,您的值是 null 而 Spring 引导初始化过程正在进行中。

Better yet define a Singleton bean using Spring @Scope("singleton") .最好使用 Spring @Scope("singleton")定义一个 Singleton bean。 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.将您的 class 更改为正常的,并让其生命周期和创建由 Spring 管理,您将更容易测试因为测试 static 类并不总是那么容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何访问 class 的私有构造函数? - How can I access a private constructor of a class? 我如何使用泛型类的构造函数 - How can i use a constructor of a generic class 如何使用具有私有构造函数的类的实例? - How to use an instance of a class that has a private constructor? 如何使用非空构造函数自动连接类? - How to autowire a class with non-empty constructor? 我可以使用 Spring 参数化 class 代替 spring 自动装配吗 - can i use Spring parameterized class used instead of spring autowire 我可以自动连接适配器类吗? - Can I Autowire an Adapter Class? 如何使用动态值实例化构造函数并自动装配它? - How to instantiate constructor with dynamic value and Autowire it? 我如何在同一个 class 的不同方法中使用私有 static 方法(对象的扩展)的返回值? (爪哇) - How can i use the return value of a private static method (extension of object) in a different method in that same class? (java) 当类只有一个私有构造函数时,如何创建代理? - How can I create a proxy when the class having only one private constructor? 如何使用反射创建具有私有字段和构造函数的类对象? - How can I make an object of class having private fields and constructor using reflection?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM