It's not possible to use @Value
on 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?
Use this simple trick to achieve what you want (way better than having the value injected into non-static setters and writing so a static field - as suggested in the accepted answer):
Use like:
ConfigUtil.INSTANCE.getValue();
Spring inject noting in static field (by default).
So you have two alternatives:
@Value
annotation to the setter.@Value
tooTo prevent ever repeating injections of the same value making a field non-static in a class that gets instantiated very often, I preferred to create a simple Singleton ConfigUtil as a workaround:
Inside the class I tried to inject the value first as a static Integer: