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?
Advertisement
Answer
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
@Valueannotation to the setter.
- and then there is the trick with the MethodInvokingFactoryBean — this example is for autowired fiels, but I guess you can adapt it for
@Valuetoo