Chintan Patel
Chintan Patel

Reputation: 739

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?

Upvotes: 5

Views: 21288

Answers (2)

pmadril
pmadril

Reputation: 196

A better way is to mimic a final aspect by using a static setter which will only set the value if it's currently null.

private static String outputPath;

public static String getOutputPath(){
   return outputPath;
}

private static setOutputPath( String op){
  if (outputPath == null) { 
      outputPath =  op;
  }
}

@Value("${outputfilepath}")
private setOutputFilePath(String outputFilePath){
  setOutputPath(outputFilePath);
}

Thanks to Walfrat comment here.

Upvotes: 0

nesteant
nesteant

Reputation: 1068

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

Upvotes: 14

Related Questions