Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject property value using @Value into static fields

Tags:

java

spring

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?

like image 681
Chintan Patel Avatar asked May 25 '15 09:05

Chintan Patel


1 Answers

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

like image 152
nesteant Avatar answered Nov 02 '22 23:11

nesteant