类 Jackson2ObjectMapperFactoryBean
- java.lang.Object
- org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean
- 所有已实现的接口:
Aware
,BeanClassLoaderAware
,FactoryBean<ObjectMapper>
,InitializingBean
,ApplicationContextAware
public class Jackson2ObjectMapperFactoryBean extends Object implements FactoryBean<ObjectMapper>, BeanClassLoaderAware, ApplicationContextAware, InitializingBean
AFactoryBean
for creating a Jackson 2.xObjectMapper
(default) orXmlMapper
(createXmlMapper
property set to true) with setters to enable or disable Jackson features from within XML configuration.It customizes Jackson defaults properties with the following ones:
MapperFeature.DEFAULT_VIEW_INCLUSION
is disabledDeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
is disabled
Example usage with
MappingJackson2HttpMessageConverter
:<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean" p:autoDetectFields="false" p:autoDetectGettersSetters="false" p:annotationIntrospector-ref="jaxbAnnotationIntrospector" /> </property> </bean>
Example usage with MappingJackson2JsonView:
<bean class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"> <property name="objectMapper"> <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean" p:failOnEmptyBeans="false" p:indentOutput="true"> <property name="serializers"> <array> <bean class="org.mycompany.MyCustomSerializer" /> </array> </property> </bean> </property> </bean>
In case there are no specific setters provided (for some rarely used options), you can still use the more general methods
setFeaturesToEnable(java.lang.Object...)
andsetFeaturesToDisable(java.lang.Object...)
.<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"> <property name="featuresToEnable"> <array> <util:constant static-field="com.fasterxml.jackson.databind.SerializationFeature.WRAP_ROOT_VALUE"/> <util:constant static-field="com.fasterxml.jackson.databind.SerializationFeature.CLOSE_CLOSEABLE"/> </array> </property> <property name="featuresToDisable"> <array> <util:constant static-field="com.fasterxml.jackson.databind.MapperFeature.USE_ANNOTATIONS"/> </array> </property> </bean>
It also automatically registers the following well-known modules if they are detected on the classpath:
- jackson-datatype-jdk7: support for Java 7 types like
Path
- jackson-datatype-jdk8: support for other Java 8 types like
Optional
- jackson-datatype-jsr310: support for Java 8 Date & Time API types
- jackson-datatype-joda: support for Joda-Time types
- jackson-module-kotlin: support for Kotlin classes and data classes
In case you want to configure Jackson's
ObjectMapper
with a customModule
, you can register one or more such Modules by class name viasetModulesToInstall(java.lang.Class<? extends com.fasterxml.jackson.databind.Module>...)
:<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"> <property name="modulesToInstall" value="myapp.jackson.MySampleModule,myapp.jackson.MyOtherModule"/> </bean
Compatible with Jackson 2.6 and higher, as of Spring 4.3.
- 从以下版本开始:
- 3.2
- 作者:
- Dmitry Katsubo, Rossen Stoyanchev, Brian Clozel, Juergen Hoeller, Tadaya Tsuyukubo, Sebastien Deleuze
字段概要
从接口继承的字段 org.springframework.beans.factory.FactoryBean
OBJECT_TYPE_ATTRIBUTE
构造器概要
构造器 构造器 说明 Jackson2ObjectMapperFactoryBean()
方法概要
所有方法 实例方法 具体方法 修饰符和类型 方法 说明 void
afterPropertiesSet()
Invoked by the containingBeanFactory
after it has set all bean properties and satisfiedBeanFactoryAware
,ApplicationContextAware
etc.ObjectMapper
getObject()
Return the singleton ObjectMapper.Class<?>
getObjectType()
Return the type of object that this FactoryBean creates, ornull
if not known in advance.boolean
isSingleton()
Is the object managed by this factory a singleton?void
setAnnotationIntrospector(AnnotationIntrospector annotationIntrospector)
Set anAnnotationIntrospector
for both serialization and deserialization.void
setApplicationContext(ApplicationContext applicationContext)
Set the builderApplicationContext
in order to autowire Jackson handlers (JsonSerializer
,JsonDeserializer
,KeyDeserializer
,TypeResolverBuilder
andTypeIdResolver
).void
setAutoDetectFields(boolean autoDetectFields)
Shortcut forMapperFeature.AUTO_DETECT_FIELDS
option.void
setAutoDetectGettersSetters(boolean autoDetectGettersSetters)
void
setBeanClassLoader(ClassLoader beanClassLoader)
Callback that supplies the beanclass loader
to a bean instance.void
setCreateXmlMapper(boolean createXmlMapper)
If set to true and no customObjectMapper
has been set, aXmlMapper
will be created using its default constructor.void
setDateFormat(DateFormat dateFormat)
Define the format for date/time with the givenDateFormat
.void
setDefaultTyping(TypeResolverBuilder<?> typeResolverBuilder)
Specify aTypeResolverBuilder
to use for Jackson's default typing.void
setDefaultUseWrapper(boolean defaultUseWrapper)
Define if a wrapper will be used for indexed (List, array) properties or not by default (only applies toXmlMapper
).void
setDefaultViewInclusion(boolean defaultViewInclusion)
Shortcut forMapperFeature.DEFAULT_VIEW_INCLUSION
option.void
setDeserializers(JsonDeserializer<?>... deserializers)
Configure custom deserializers.void
setDeserializersByType(Map<Class<?>,JsonDeserializer<?>> deserializers)
Configure custom deserializers for the given types.void
setFactory(JsonFactory factory)
Define theJsonFactory
to be used to create theObjectMapper
instance.void
setFailOnEmptyBeans(boolean failOnEmptyBeans)
Shortcut forSerializationFeature.FAIL_ON_EMPTY_BEANS
option.void
setFailOnUnknownProperties(boolean failOnUnknownProperties)
Shortcut forDeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
option.void
setFeaturesToDisable(Object... featuresToDisable)
Specify features to disable.void
setFeaturesToEnable(Object... featuresToEnable)
Specify features to enable.void
setFilters(FilterProvider filters)
Set the global filters to use in order to support@JsonFilter
annotated POJO.void
setFindModulesViaServiceLoader(boolean findModules)
Set whether to let Jackson find available modules via the JDK ServiceLoader, based on META-INF metadata in the classpath.void
setHandlerInstantiator(HandlerInstantiator handlerInstantiator)
Customize the construction of Jackson handlers (JsonSerializer
,JsonDeserializer
,KeyDeserializer
,TypeResolverBuilder
andTypeIdResolver
).void
setIndentOutput(boolean indentOutput)
Shortcut forSerializationFeature.INDENT_OUTPUT
option.void
setLocale(Locale locale)
Override the defaultLocale
to use for formatting.void
setMixIns(Map<Class<?>,Class<?>> mixIns)
Add mix-in annotations to use for augmenting specified class or interface.void
setModules(List<Module> modules)
Set a complete list of modules to be registered with theObjectMapper
.void
setModulesToInstall(Class<? extends Module>... modules)
Specify one or more modules by class (or class name in XML) to be registered with theObjectMapper
.void
setObjectMapper(ObjectMapper objectMapper)
Set theObjectMapper
instance to use.void
setPropertyNamingStrategy(PropertyNamingStrategy propertyNamingStrategy)
Specify aPropertyNamingStrategy
to configure theObjectMapper
with.void
setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include serializationInclusion)
Set a custom inclusion strategy for serialization.void
setSerializers(JsonSerializer<?>... serializers)
Configure custom serializers.void
setSerializersByType(Map<Class<?>,JsonSerializer<?>> serializers)
Configure custom serializers for the given types.void
setSimpleDateFormat(String format)
Define the date/time format with aSimpleDateFormat
.void
setTimeZone(TimeZone timeZone)
Override the defaultTimeZone
to use for formatting.
构造器详细资料
Jackson2ObjectMapperFactoryBean
public Jackson2ObjectMapperFactoryBean()
方法详细资料
setObjectMapper
public void setObjectMapper(ObjectMapper objectMapper)
Set theObjectMapper
instance to use. If not set, theObjectMapper
will be created using its default constructor.
setCreateXmlMapper
public void setCreateXmlMapper(boolean createXmlMapper)
If set to true and no customObjectMapper
has been set, aXmlMapper
will be created using its default constructor.- 从以下版本开始:
- 4.1
setFactory
public void setFactory(JsonFactory factory)
Define theJsonFactory
to be used to create theObjectMapper
instance.- 从以下版本开始:
- 5.0
setDateFormat
public void setDateFormat(DateFormat dateFormat)
Define the format for date/time with the givenDateFormat
.Note: Setting this property makes the exposed
ObjectMapper
non-thread-safe, according to Jackson's thread safety rules.
setSimpleDateFormat
public void setSimpleDateFormat(String format)
Define the date/time format with aSimpleDateFormat
.Note: Setting this property makes the exposed
ObjectMapper
non-thread-safe, according to Jackson's thread safety rules.
setLocale
public void setLocale(Locale locale)
Override the defaultLocale
to use for formatting. Default value used isLocale.getDefault()
.- 从以下版本开始:
- 4.1.5
setTimeZone
public void setTimeZone(TimeZone timeZone)
Override the defaultTimeZone
to use for formatting. Default value used is UTC (NOT local timezone).- 从以下版本开始:
- 4.1.5
setAnnotationIntrospector
public void setAnnotationIntrospector(AnnotationIntrospector annotationIntrospector)
Set anAnnotationIntrospector
for both serialization and deserialization.
setPropertyNamingStrategy
public void setPropertyNamingStrategy(PropertyNamingStrategy propertyNamingStrategy)
Specify aPropertyNamingStrategy
to configure theObjectMapper
with.- 从以下版本开始:
- 4.0.2
setDefaultTyping
public void setDefaultTyping(TypeResolverBuilder<?> typeResolverBuilder)
Specify aTypeResolverBuilder
to use for Jackson's default typing.- 从以下版本开始:
- 4.2.2
setSerializationInclusion
public void setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include serializationInclusion)
Set a custom inclusion strategy for serialization.- 另请参阅:
JsonInclude.Include
setFilters
public void setFilters(FilterProvider filters)
Set the global filters to use in order to support@JsonFilter
annotated POJO.- 从以下版本开始:
- 4.2
- 另请参阅:
Jackson2ObjectMapperBuilder.filters(FilterProvider)
setMixIns
public void setMixIns(Map<Class<?>,Class<?>> mixIns)
Add mix-in annotations to use for augmenting specified class or interface.- 参数:
mixIns
- a Map of entries with target classes (or interface) whose annotations to effectively override as key and mix-in classes (or interface) whose annotations are to be "added" to target's annotations as value.- 从以下版本开始:
- 4.1.2
- 另请参阅:
ObjectMapper.addMixInAnnotations(Class, Class)
setSerializers
public void setSerializers(JsonSerializer<?>... serializers)
Configure custom serializers. Each serializer is registered for the type returned byJsonSerializer.handledType()
, which must not benull
.
setSerializersByType
public void setSerializersByType(Map<Class<?>,JsonSerializer<?>> serializers)
Configure custom serializers for the given types.
setDeserializers
public void setDeserializers(JsonDeserializer<?>... deserializers)
Configure custom deserializers. Each deserializer is registered for the type returned byJsonDeserializer.handledType()
, which must not benull
.- 从以下版本开始:
- 4.3
- 另请参阅:
setDeserializersByType(Map)
setDeserializersByType
public void setDeserializersByType(Map<Class<?>,JsonDeserializer<?>> deserializers)
Configure custom deserializers for the given types.
setAutoDetectFields
public void setAutoDetectFields(boolean autoDetectFields)
Shortcut forMapperFeature.AUTO_DETECT_FIELDS
option.
setAutoDetectGettersSetters
public void setAutoDetectGettersSetters(boolean autoDetectGettersSetters)
setDefaultViewInclusion
public void setDefaultViewInclusion(boolean defaultViewInclusion)
Shortcut forMapperFeature.DEFAULT_VIEW_INCLUSION
option.- 从以下版本开始:
- 4.1
setFailOnUnknownProperties
public void setFailOnUnknownProperties(boolean failOnUnknownProperties)
Shortcut forDeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
option.- 从以下版本开始:
- 4.1.1
setFailOnEmptyBeans
public void setFailOnEmptyBeans(boolean failOnEmptyBeans)
Shortcut forSerializationFeature.FAIL_ON_EMPTY_BEANS
option.
setIndentOutput
public void setIndentOutput(boolean indentOutput)
Shortcut forSerializationFeature.INDENT_OUTPUT
option.
setDefaultUseWrapper
public void setDefaultUseWrapper(boolean defaultUseWrapper)
Define if a wrapper will be used for indexed (List, array) properties or not by default (only applies toXmlMapper
).- 从以下版本开始:
- 4.3
setFeaturesToEnable
public void setFeaturesToEnable(Object... featuresToEnable)
Specify features to enable.
setFeaturesToDisable
public void setFeaturesToDisable(Object... featuresToDisable)
Specify features to disable.
setModules
public void setModules(List<Module> modules)
Set a complete list of modules to be registered with theObjectMapper
.Note: If this is set, no finding of modules is going to happen - not by Jackson, and not by Spring either (see
setFindModulesViaServiceLoader(boolean)
). As a consequence, specifying an empty list here will suppress any kind of module detection.Specify either this or
setModulesToInstall(java.lang.Class<? extends com.fasterxml.jackson.databind.Module>...)
, not both.- 从以下版本开始:
- 4.0
- 另请参阅:
Module
setModulesToInstall
public void setModulesToInstall(Class<? extends Module>... modules)
Specify one or more modules by class (or class name in XML) to be registered with theObjectMapper
.Modules specified here will be registered after Spring's autodetection of JSR-310 and Joda-Time, or Jackson's finding of modules (see
setFindModulesViaServiceLoader(boolean)
), allowing to eventually override their configuration.Specify either this or
setModules(java.util.List<com.fasterxml.jackson.databind.Module>)
, not both.- 从以下版本开始:
- 4.0.1
- 另请参阅:
Module
setFindModulesViaServiceLoader
public void setFindModulesViaServiceLoader(boolean findModules)
Set whether to let Jackson find available modules via the JDK ServiceLoader, based on META-INF metadata in the classpath. Requires Jackson 2.2 or higher.If this mode is not set, Spring's Jackson2ObjectMapperFactoryBean itself will try to find the JSR-310 and Joda-Time support modules on the classpath - provided that Java 8 and Joda-Time themselves are available, respectively.
- 从以下版本开始:
- 4.0.1
- 另请参阅:
ObjectMapper.findModules()
setBeanClassLoader
public void setBeanClassLoader(ClassLoader beanClassLoader)
从接口复制的说明:BeanClassLoaderAware
Callback that supplies the beanclass loader
to a bean instance.Invoked after the population of normal bean properties but before an initialization callback such as
InitializingBean's
InitializingBean.afterPropertiesSet()
method or a custom init-method.- 指定者:
setBeanClassLoader
在接口中BeanClassLoaderAware
- 参数:
beanClassLoader
- the owning class loader
setHandlerInstantiator
public void setHandlerInstantiator(HandlerInstantiator handlerInstantiator)
Customize the construction of Jackson handlers (JsonSerializer
,JsonDeserializer
,KeyDeserializer
,TypeResolverBuilder
andTypeIdResolver
).- 从以下版本开始:
- 4.1.3
- 另请参阅:
setApplicationContext(ApplicationContext)
setApplicationContext
public void setApplicationContext(ApplicationContext applicationContext)
Set the builderApplicationContext
in order to autowire Jackson handlers (JsonSerializer
,JsonDeserializer
,KeyDeserializer
,TypeResolverBuilder
andTypeIdResolver
).- 指定者:
setApplicationContext
在接口中ApplicationContextAware
- 参数:
applicationContext
- the ApplicationContext object to be used by this object- 从以下版本开始:
- 4.1.3
- 另请参阅:
Jackson2ObjectMapperBuilder.applicationContext(ApplicationContext)
,SpringHandlerInstantiator
afterPropertiesSet
public void afterPropertiesSet()
从接口复制的说明:InitializingBean
Invoked by the containingBeanFactory
after it has set all bean properties and satisfiedBeanFactoryAware
,ApplicationContextAware
etc.This method allows the bean instance to perform validation of its overall configuration and final initialization when all bean properties have been set.
- 指定者:
afterPropertiesSet
在接口中InitializingBean
getObject
@Nullable public ObjectMapper getObject()
Return the singleton ObjectMapper.- 指定者:
getObject
在接口中FactoryBean<ObjectMapper>
- 返回:
- an instance of the bean (can be
null
) - 另请参阅:
FactoryBeanNotInitializedException
getObjectType
public Class<?> getObjectType()
从接口复制的说明:FactoryBean
Return the type of object that this FactoryBean creates, ornull
if not known in advance.This allows one to check for specific types of beans without instantiating objects, for example on autowiring.
In the case of implementations that are creating a singleton object, this method should try to avoid singleton creation as far as possible; it should rather estimate the type in advance. For prototypes, returning a meaningful type here is advisable too.
This method can be called before this FactoryBean has been fully initialized. It must not rely on state created during initialization; of course, it can still use such state if available.
NOTE: Autowiring will simply ignore FactoryBeans that return
null
here. Therefore it is highly recommended to implement this method properly, using the current state of the FactoryBean.- 指定者:
getObjectType
在接口中FactoryBean<ObjectMapper>
- 返回:
- the type of object that this FactoryBean creates, or
null
if not known at the time of the call - 另请参阅:
ListableBeanFactory.getBeansOfType(java.lang.Class<T>)
isSingleton
public boolean isSingleton()
从接口复制的说明:FactoryBean
Is the object managed by this factory a singleton? That is, willFactoryBean.getObject()
always return the same object (a reference that can be cached)?NOTE: If a FactoryBean indicates to hold a singleton object, the object returned from
getObject()
might get cached by the owning BeanFactory. Hence, do not returntrue
unless the FactoryBean always exposes the same reference.The singleton status of the FactoryBean itself will generally be provided by the owning BeanFactory; usually, it has to be defined as singleton there.
NOTE: This method returning
false
does not necessarily indicate that returned objects are independent instances. An implementation of the extendedSmartFactoryBean
interface may explicitly indicate independent instances through itsSmartFactoryBean.isPrototype()
method. PlainFactoryBean
implementations which do not implement this extended interface are simply assumed to always return independent instances if theisSingleton()
implementation returnsfalse
.The default implementation returns
true
, since aFactoryBean
typically manages a singleton instance.- 指定者:
isSingleton
在接口中FactoryBean<ObjectMapper>
- 返回:
- whether the exposed object is a singleton
- 另请参阅:
FactoryBean.getObject()
,SmartFactoryBean.isPrototype()