我需要在不重启服务器的情况下从属性文件动态地向hashmap中添加键和值。所以我在我的对象中创建了一个静态哈希图,它在服务器启动时从文件加载数据。因此,在后续添加属性时,我将更新这个hashmap。这是我的HashMap实例化。
private static Map<String, String> map = new HashMap<>();
所以现在,当我添加一个属性时,我初始化了映射,现在如果我执行我的main方法,因为它是一个相同的类加载器,当我在DEBUG模式下查看时,我仍然会在我的映射中看到一个新值。例如:如果我将Europe=EU添加为新属性,我将在调试模式中看到此值与其他属性为[Europe=EU, India= in],如果我运行line map.get("Europe"),我将获得值为null。
我不清楚这种行为。是没有提交到实例还是我做错了什么。下面是我的代码:
public class CountryMap {
private static Map<String, String> map = new HashMap<>();
private static final CountryMap countrymap = new CountryMap();
static {
initmap();
}
private static void initmap() {
IPropertyReader reader = (IPropertyReader) MyAppContext
.getInstance().getBean("propreader"); //To read from location files
try {
Properties props = reader.loadPropertyFile();
Set<Entry<Object, Object>> propset = props.entrySet();
for (Entry<Object, Object> entry : propset) {
map.put((String) entry.getKey(),
entry.getValue().toString());
}
} catch (Throwable e) {
e.printStackTrace();
}
}
public static CountryMap getInstance() {
return countrymap;
}
public String getvalue(String key) {
return map.get(key);
}
public void addtomap(String key, String value) {
map.put(key, value);
}
}
你真的需要hashmap吗?也许可以使用一些已经存在的东西,比如公共配置和它们的重新加载策略?https://commons.apache.org/proper/commons-configuration/userguide_v1.10/howto_filebased.html