I have a class that I wanted to have static final
variables.
public static final Map<String, Long> ID_MAP;
I wanted to be able to inject the map via Spring. This can't be done b/c it is a static final
. My alternative was to declare it as static
and use Spring with a setter. Something like
public void setIDMapSpring (long iDMapSpring){
ID_MAP = iDMapSpring;
This, however, means that another class can come change the value. Are there any alternatives that I can try. I was thinking of having a Singleton with the Map as a final
field but I've still to figure out how to pass the Map, and possibly other variables I want marked final
, to the getInstance
method. Also, I struggle to find the simplest and least complex solution.
将地图设为字段并注入单例。
If you're concerned about an outside class changing the value after Spring sets it, you could integrate a flag into your class that only lets the field be set once. Say you initialize a static AtomicBoolean
called "CAN_SET_ID_MAP" to true. Then, in the map's setter:
if (CAN_SET_ID_MAP.compareAndSet (true, false)) {
ID_MAP = iDMapSpring;
} else {
throw new IllegalStateException ("ID_MAP already set");
}
There are other ways to do it. You probably want to use a thread-safe form of protection regardless.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.