From ff90e4eb6809599ab76812e1b265a2b79142da3f Mon Sep 17 00:00:00 2001 From: xiao Date: Tue, 22 Oct 2024 14:14:33 +0800 Subject: [PATCH] Optimize the usage of JacksonMongoSessionConverter to prevent duplicate MongoSession Document saves when a custom ObjectMapper is provided.https://github.com/spring-projects/spring-session/issues/3185 --- .../data/mongo/JacksonMongoSessionConverter.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/spring-session-data-mongodb/src/main/java/org/springframework/session/data/mongo/JacksonMongoSessionConverter.java b/spring-session-data-mongodb/src/main/java/org/springframework/session/data/mongo/JacksonMongoSessionConverter.java index 986634200..649696d8e 100644 --- a/spring-session-data-mongodb/src/main/java/org/springframework/session/data/mongo/JacksonMongoSessionConverter.java +++ b/spring-session-data-mongodb/src/main/java/org/springframework/session/data/mongo/JacksonMongoSessionConverter.java @@ -44,6 +44,7 @@ import org.springframework.security.jackson2.SecurityJackson2Modules; import org.springframework.session.FindByIndexNameSessionRepository; import org.springframework.util.Assert; +import org.springframework.util.ClassUtils; /** * {@code AbstractMongoSessionConverter} implementation using Jackson. @@ -51,6 +52,7 @@ * @author Jakub Kubrynski * @author Greg Turnquist * @author Michael Ruf + * @author TiQuan Hu * @since 1.2 */ public class JacksonMongoSessionConverter extends AbstractMongoSessionConverter { @@ -93,9 +95,12 @@ protected Query getQueryForIndex(String indexName, Object indexValue) { } private ObjectMapper buildObjectMapper() { - ObjectMapper objectMapper = new ObjectMapper(); + configureObjectMapper(objectMapper); + return objectMapper; + } + public static void configureObjectMapper(ObjectMapper objectMapper) { // serialize fields instead of properties objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE); objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); @@ -105,11 +110,9 @@ private ObjectMapper buildObjectMapper() { objectMapper.setPropertyNamingStrategy(new MongoIdNamingStrategy()); - objectMapper.registerModules(SecurityJackson2Modules.getModules(getClass().getClassLoader())); + objectMapper.registerModules(SecurityJackson2Modules.getModules(ClassUtils.getDefaultClassLoader())); objectMapper.addMixIn(MongoSession.class, MongoSessionMixin.class); objectMapper.addMixIn(HashMap.class, HashMapMixin.class); - - return objectMapper; } @Override