An alternative to @Value annotation in static function
22,886
Solution 1
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.
- and then there is the trick with the MethodInvokingFactoryBean -- this example is for autowired fiels, but I guess you can adapt it for
@Value
too
Solution 2
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):
@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 like:
ConfigUtil.INSTANCE.getValue();
Author by
Sanghyun Lee
Updated on July 09, 2022Comments
-
Sanghyun Lee almost 2 years
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? -
Sanghyun Lee almost 13 yearsCan I access to properties value from static function in non-spring way?
-
Ralph almost 13 years@Sangdol: via the application context: sujitpal.blogspot.com/2007/03/…
-
membersound over 7 yearsI tried this and it does not work (of course, because you construct the
ConfigUtil
using thenew
operator. -
Gaetano Piazzolla about 6 yearsTrue, it does not work even if it's annotated with @configurable.
-
Adriaan Koster over 4 yearsUpvoted for food solution to OP's question (given that static context is required). However I would not call this a 'trick' but mention the pattern's name: Singleton: en.wikipedia.org/wiki/Singleton_pattern
-
jack3694078 over 4 years
NullPointException
is thrown becauseINSTANCE
is null when I test this code. I'm suspectingConfigUtil
needs to be injected itself for@PostConstruct
to work (which kinds of defeat the purpose of using static methods) -
Vikki almost 4 years@jack3694078 I also got NullPointException