5

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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Chintan Patel
  • 729
  • 3
  • 14
  • 31
  • You cannot. Create a singleton object instead. – Gábor Bakos May 25 '15 at 10:00
  • 1
    possible duplicate of [How to make spring inject value into a static field](http://stackoverflow.com/questions/11324372/how-to-make-spring-inject-value-into-a-static-field) – nilesh virkar May 25 '15 at 10:01
  • there is another approach to access variables of property files using @PropertySource please refer this link www.mkyong.com/spring/spring-propertysoaurces-example/ – Dev May 25 '15 at 10:07

2 Answers2

14

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

nesteant
  • 1,070
  • 9
  • 16
0

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.

pmadril
  • 126
  • 2
  • 5