java - Web 服务器启动时将 JSON 文件转换为 java 对象
问题描述
我有一个 JSON 文件,我正在使用 Object Mapper 将其转换为 JAVA 对象,如下所示:-
String agentName = Request.getAgentName();
ObjectMapper mapper = new ObjectMapper();
agent = mapper.readValue(new File(agentName), Agent.class);
这些工作正常,但问题是,对于我将 json 转换为 java 对象的每个请求,我想在我的 Web 服务器启动时执行一次。我该怎么做,这是一个休息应用程序。
解决方案
这可能是一个可能的解决方案,它使用带有地图的 Singleton 类,其中包含根据请求初始化的所有代理。
public class Agents {
private static Agents theInstance;
private final Map<String, Agent> AGENTS_MAP;
private Agents() {
this.AGENTS_MAP = new HashMap<>();
}
public static Agents getInstance() {
if (theInstance == null) {
theInstance = new Agents();
}
return theInstance;
}
public Agent getAgent(String agentName) {
if (!AGENTS_MAP.containsKey(agentName) {
initAgent(agentName);
}
return AGENTS_MAP.get(agentName);
}
// TODO handle errors
private static void initAgent(String agentName) {
ObjectMapper mapper = new ObjectMapper();
Agent agent = mapper.readValue(new File(agentName), Agent.class);
AGENTS_MAP.put(agentName, agent);
}
}
推荐阅读
- python - 来自终端的 python virtualenv 不工作,但从 pycharm 工作
- php - 为什么我的 PHP 会话变量不再起作用?
- python-3.x - 如何遍历熊猫数据框以形成嵌套的json?
- django - aadsts50011:请求中指定的回复 url 与为应用程序配置的回复 url 不匹配:'App id'。本地主机配置
- google-apps-script - 谷歌表格,自动删除单元格中的前撇号
- function - PowerShell - 我第一次尝试函数时找不到函数
- ruby-on-rails - Rails:与同一模型的双重关联
- android - 如何使自定义xml可绘制
- javascript - 如何用变量替换数组名称?
- azure - 无法安装 Azure AD 应用程序代理连接器