Allow custom ObjectMapper to be injected

Jackson-based session converter now allows a custom ObjectMapper to be injected.

Resolves #27.
This commit is contained in:
Greg Turnquist
2018-08-03 10:22:55 -05:00
parent 9e902ea50f
commit a2bfa4d39d
2 changed files with 36 additions and 2 deletions

View File

@@ -28,6 +28,7 @@ import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.security.jackson2.SecurityJackson2Modules;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.util.Assert;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
@@ -65,6 +66,12 @@ public class JacksonMongoSessionConverter extends AbstractMongoSessionConverter
this.objectMapper.registerModules(modules);
}
public JacksonMongoSessionConverter(ObjectMapper objectMapper) {
Assert.notNull(objectMapper, "ObjectMapper can NOT be null!");
this.objectMapper = objectMapper;
}
protected Query getQueryForIndex(String indexName, Object indexValue) {
if (FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME.equals(indexName)) {

View File

@@ -15,11 +15,16 @@
*/
package org.springframework.session.data.mongo;
import static org.assertj.core.api.Assertions.*;
import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import java.lang.reflect.Field;
import org.junit.Test;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.ReflectionUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.DBObject;
/**
@@ -59,5 +64,27 @@ public class JacksonMongoSessionConverterTest extends AbstractMongoSessionConver
assertThat(cart.getQueryObject().get("attrs.cart")).isEqualTo("my-cart");
}
@Test
public void shouldAllowCustomObjectMapper() {
// given
ObjectMapper myMapper = new ObjectMapper();
// when
JacksonMongoSessionConverter converter = new JacksonMongoSessionConverter(myMapper);
// then
Field objectMapperField = ReflectionUtils.findField(JacksonMongoSessionConverter.class, "objectMapper");
ReflectionUtils.makeAccessible(objectMapperField);
ObjectMapper converterMapper = (ObjectMapper) ReflectionUtils.getField(objectMapperField, converter);
assertThat(converterMapper).isEqualTo(myMapper);
}
@Test(expected = IllegalArgumentException.class)
public void shouldNotAllowNullObjectMapperToBeInjected() {
new JacksonMongoSessionConverter((ObjectMapper) null);
}
}