如果你想繼續使用Spring,你可以使用@Component
來創建一個簡單的組件。默認情況下,所有組件都是單例。您可以使用@PostConstruct
來初始化數據。下面是一個例子。我使用String
作爲映射關鍵字,但您可以修改它以匹配您的應用程序。
@Component
public class MyMap {
private Map<String, Object> theMap = new HashMap<>();
// PostConstruct runs after the application context instantiates the bean
@PostConstruct
public void init() {
// initialize the data in theMap
}
public Object get(String key) {
return theMap.get(key);
}
}
然後,您可以使用@Autowired
註解或您的應用程序上下文檢索豆:
public class AnotherClass {
@Autowired
MyMap myMap;
// ...
}
如果你想避免春季,另一種選擇是創建一個簡單的Java單。這裏有一個例子
public class MyMap {
private final static Map<String, Object> theMap = new HashMap<>();
// Use a static block to initialize the map with data
static {
// populate theMap with data
}
public Object get(String key) {
return theMap.get(key);
}
}
有一點需要注意的是,如果您的地圖永遠不會真正得到更新,那麼你將需要處理的併發讀取和更新。
默認情況下,Spring bean是單身人士。只需將它製作成Spring bean並將其注入需要的地方即可。 –