Skip to content
Advertisement

How to inject property value using @Value into static fields

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:

<context:property-placeholder location="classpath:properties/config.properties"/>

Now I need to set its value to static field using @Value annotation.

@Value("${outputfilepath}")
private static String outputPath;

How can I achieve this?

Advertisement

Answer

The only way is to use setter for this value

@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

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement