From 49fc72770684ab014369b2f7ef6d9ae66f1d22f2 Mon Sep 17 00:00:00 2001 From: Phillip Webb Date: Sat, 21 Jan 2017 07:05:27 -0800 Subject: [PATCH] Lazy initialize JacksonJsonParser ObjectMapper Update `JacksonJsonParser` to that the `ObjectMapper` is only initialized on first use. This performance optimization helps with startup times if nothing uses the parser. Fixes gh-8074 --- .../boot/json/JacksonJsonParser.java | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/spring-boot/src/main/java/org/springframework/boot/json/JacksonJsonParser.java b/spring-boot/src/main/java/org/springframework/boot/json/JacksonJsonParser.java index c7a7c162daf..107f725d979 100644 --- a/spring-boot/src/main/java/org/springframework/boot/json/JacksonJsonParser.java +++ b/spring-boot/src/main/java/org/springframework/boot/json/JacksonJsonParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,12 +34,12 @@ public class JacksonJsonParser implements JsonParser { private static final TypeReference LIST_TYPE = new ListTypeReference(); - private final ObjectMapper objectMapper = new ObjectMapper(); + private ObjectMapper objectMapper; // Late binding @Override public Map parseMap(String json) { try { - return this.objectMapper.readValue(json, MAP_TYPE); + return getObjectMapper().readValue(json, MAP_TYPE); } catch (Exception ex) { throw new IllegalArgumentException("Cannot parse JSON", ex); @@ -49,13 +49,20 @@ public class JacksonJsonParser implements JsonParser { @Override public List parseList(String json) { try { - return this.objectMapper.readValue(json, LIST_TYPE); + return getObjectMapper().readValue(json, LIST_TYPE); } catch (Exception ex) { throw new IllegalArgumentException("Cannot parse JSON", ex); } } + private ObjectMapper getObjectMapper() { + if (this.objectMapper == null) { + this.objectMapper = new ObjectMapper(); + } + return this.objectMapper; + } + private static class MapTypeReference extends TypeReference> { };