java 如何使用@Value 将属性值注入静态字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30435672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to inject property value using @Value into static fields
提问by Chintan Patel
I have one property file config.properties which is configured using spring property placeholder. This is how it's configured in my spring configuration file:
我有一个使用 spring 属性占位符配置的属性文件 config.properties。这是它在我的 spring 配置文件中的配置方式:
<context:property-placeholder location="classpath:properties/config.properties"/>
Now I need to set its value to staticfield using @Value annotation.
现在我需要使用@Value 注释将其值设置为静态字段。
@Value("${outputfilepath}")
private static String outputPath;
How can I achieve this?
我怎样才能做到这一点?
回答by nesteant
The only way is to use setter for this value
唯一的方法是对这个值使用 setter
@Value("${value}")
public void setOutputPath(String outputPath) {
AClass.outputPath = outputPath;
}
However you should avoid doing this. Spring is not designed for static injections. Thus you should use another way to set this field at start of your application, e.g. constructor. Anyway @Value annotation uses springs PropertyPlaceholder which is still resolved after static fields are initialized. Thus you won't have any advantages for this construction
但是,您应该避免这样做。Spring 不是为静态注入而设计的。因此,您应该使用另一种方式在应用程序开始时设置此字段,例如构造函数。无论如何@Value 注释使用 springs PropertyPlaceholder,它在静态字段初始化后仍然可以解决。因此,您不会对这种结构有任何优势