How to inject property value using @Value into static fields
I have one properties file config.properties which is configured with spring property placeholder. This is how it is configured in my spring config file:
<context:property-placeholder location="classpath:properties/config.properties"/>
Now I need to set its value to a static field using @Value annotation.
@Value("${outputfilepath}")
private static String outputPath;
How can I achieve this?
+3
source to share
1 answer
The only way is to use a setter for that value
@Value("${value}")
public void setOutputPath(String outputPath) {
AClass.outputPath = outputPath;
}
However, you should avoid this. Spring is not designed for static injection. So you have to use a different way of setting this field at the start of your application, eg. constructor. In any case, the @Value annotation uses PropertyPlaceholder springs, which are still resolved after static fields are initialized. Thus, you will not have any advantages for this design.
+12
source to share