我有一个类ConfigFactory
,它可以通过 vert.x conf 模块从 JSON 文件中给我一些配置。
public class ConfigFactory {
private static JsonObject result = new JsonObject();
static {
ConfigStoreOptions fileStore = new ConfigStoreOptions()
.setType("file")
.setOptional(true)
.setFormat("json")
.setConfig(new JsonObject().put("path", "conf/config.json"));
ConfigRetrieverOptions options = new ConfigRetrieverOptions().addStore(fileStore);
ConfigRetriever retriever = ConfigRetriever.create(VertxSingleton.VERTX, options);
retriever.getConfig(ar -> {
if (ar.failed()) {
throw new RuntimeException("Config get error! Something went wring during getting the config");
} else {
result.mergeIn(ar.result());
}
});
}
public static JsonObject getHttpConfig() {
BiFunction<Integer, String, JsonObject> httpConfigFile = (port, host) -> new JsonObject()
.put("port", port).put("host", host);
if (!result.isEmpty()) {
JsonObject http = result.getJsonObject("http");
return httpConfigFile.apply(http.getInteger("port"), http.getString("host"));
} else {
throw new RuntimeException("HTTP Config get error! Something went wring during getting the config");
}
}
}
但是在 Verticle 中,我使用JsonObject httpConfig = ConfigFactory.getHttpConfig();
,它会给我异常
HTTP Config get error! Something went wring during getting the config
。此时,result
是空的。
我发现静态方法getHttpConfig
在静态代码块之前运行。大约一秒钟,静态代码块将运行。那个时候,result
还不是空的。
你能帮助我吗?谢谢!