[英]Java Static final alternatives for use with Spring DI
I have a class that I wanted to have static final
variables. 我有一个想拥有
static final
变量的类。
public static final Map<String, Long> ID_MAP;
I wanted to be able to inject the map via Spring. 我希望能够通过Spring注入地图。 This can't be done b/c it is a
static final
. b / c无法完成,因为这是
static final
。 My alternative was to declare it as static
and use Spring with a setter. 我的替代方法是将其声明为
static
并使用带有setter的Spring。 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. 我当时在考虑将Map作为
final
字段使用Singleton,但我仍想弄清楚如何将Map以及可能要标记为final
其他变量传递给getInstance
方法。 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. 如果您担心在Spring设置之后外部类会更改该值,则可以将一个标志集成到您的类中,该标志只能将该字段设置一次。 Say you initialize a static
AtomicBoolean
called "CAN_SET_ID_MAP" to true. 假设您将名为“ CAN_SET_ID_MAP”的静态
AtomicBoolean
初始化为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.
无论如何,您可能都想使用线程安全的保护形式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.