Alternative to @Value annotation in static function

Cannot use @Value for a static variable.

 @Value("${some.value}") static private int someValue; static public void useValue() { System.out.println(someValue); } 

When I do this, 0 is printed. So what is a good alternative to this?

+7
source share
3 answers

Spring enter a note in a static field (default).

So you have two alternatives:

  • (best) make the field non-static
  • (ugly hack) add a single static setter that writes to a static field and add the @Value annotation to the installer.

+9
source

Use this simple trick to achieve what you want (the path is better than the value entered in non-static setters, and writing such a static field - as suggested in the accepted answer):

 @Service public class ConfigUtil { public static ConfigUtil INSTANCE; @Value("${some.value}) private String value; @PostConstruct public void init() { INSTANCE = this; } public String getValue() { return value; } } 

Use as:

ConfigUtil.INSTANCE.getValue();

+2
source

To prevent repeated injections of the same value by creating a non-static field in the class that gets the instance very often, I chose to create a simple Singleton ConfigUtil as a workaround:

 package de.agitos.app.util; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.beans.factory.annotation.Value; /** * Helper class to get injected configuration values from static methods * * @author Florian Sager * */ @Configurable public class ConfigUtil { private static ConfigUtil instance = new ConfigUtil(); public static ConfigUtil getInstance() { return instance; } private @Value("${my.value1}") Integer value1; public Integer getValue1() { return value1; } } 

Inside the class, I tried to enter the value first as a static integer:

 private static Integer value1 = ConfigUtil.getInstance().getValue1(); 
+1
source

All Articles