Hugh Lee Hugh Lee - 1 year ago 105
Java Question

An alternative to @Value annotation in static function

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?

Answer Source

Spring inject noting in static field (by default).

So you have two alternatives:

  • (the better one) make the field non static
  • (the ugly hack) add an none static setter which writes in the static field, and add the @Value annotation to the setter.