如果你想继续使用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并将其注入需要的地方即可。 –