org.springframework.oxm.jaxb

## Class Jaxb2Marshaller

- java.lang.Object
- - org.springframework.oxm.jaxb.Jaxb2Marshaller

- All Implemented Interfaces:
    Aware, BeanClassLoaderAware, InitializingBean, GenericMarshaller, GenericUnmarshaller, Marshaller, MimeMarshaller, MimeUnmarshaller, Unmarshaller

      public class Jaxb2Marshaller
      extends Object
      implements MimeMarshaller, MimeUnmarshaller, GenericMarshaller, GenericUnmarshaller, BeanClassLoaderAware, InitializingBean

  Implementation of the `GenericMarshaller` interface for JAXB 2.2.

  The typical usage will be to set either the "contextPath" or the "classesToBeBound" property on this bean, possibly customize the marshaller and unmarshaller by setting properties, schemas, adapters, and listeners, and to refer to it.

  Since:
    3.0
  Author:
    Arjen Poutsma, Juergen Hoeller, Rossen Stoyanchev
  See Also:
    `setContextPath(java.lang.String)`, `setClassesToBeBound(java.lang.Class<?>...)`, `setJaxbContextProperties(java.util.Map<java.lang.String, ?>)`, `setMarshallerProperties(java.util.Map<java.lang.String, ?>)`, `setUnmarshallerProperties(java.util.Map<java.lang.String, ?>)`, `setSchema(org.springframework.core.io.Resource)`, `setSchemas(org.springframework.core.io.Resource...)`, `setMarshallerListener(javax.xml.bind.Marshaller.Listener)`, `setUnmarshallerListener(javax.xml.bind.Unmarshaller.Listener)`, `setAdapters(javax.xml.bind.annotation.adapters.XmlAdapter<?, ?>...)`

- - ### Field Summary

    Fields
    Modifier and Type | Field and Description
    --- | ---
    `protected Log` | `logger` Logger available to subclasses.

  - ### Constructor Summary

    Constructors
    Constructor and Description
    `Jaxb2Marshaller()`

  - ### Method Summary

    All Methods Instance Methods Concrete Methods
    Modifier and Type | Method and Description
    --- | ---
    `void` | `afterPropertiesSet()` Invoked by the containing `BeanFactory` after it has set all bean properties and satisfied `BeanFactoryAware`, `ApplicationContextAware` etc.
    `protected XmlMappingException` | `convertJaxbException(JAXBException ex)` Convert the given `JAXBException` to an appropriate exception from the `org.springframework.oxm` hierarchy.
    `Marshaller` | `createMarshaller()` Return a newly created JAXB marshaller.
    `Unmarshaller` | `createUnmarshaller()` Return a newly created JAXB unmarshaller.
    `Class<?>[]` | `getClassesToBeBound()` Return the list of Java classes to be recognized by a newly created JAXBContext.
    `String` | `getContextPath()` Return the JAXB context path.
    `JAXBContext` | `getJaxbContext()` Return the JAXBContext used by this marshaller, lazily building it if necessary.
    `String[]` | `getPackagesToScan()` Return the packages to search for JAXB2 annotations.
    `protected void` | `initJaxbMarshaller(Marshaller marshaller)` Template method that can be overridden by concrete JAXB marshallers for custom initialization behavior.
    `protected void` | `initJaxbUnmarshaller(Unmarshaller unmarshaller)` Template method that can be overridden by concrete JAXB marshallers for custom initialization behavior.
    `boolean` | `isProcessExternalEntities()` Return whether XML external entities are allowed.
    `boolean` | `isSupportDtd()` Return whether DTD parsing is supported.
    `void` | `marshal(Object graph, Result result)` Marshal the object graph with the given root into the provided `Result`.
    `void` | `marshal(Object graph, Result result, MimeContainer mimeContainer)` Marshals the object graph with the given root into the provided `Result`, writing binary data to a `MimeContainer`.
    `void` | `setAdapters(XmlAdapter<?,?>... adapters)` Specify the `XmlAdapter`s to be registered with the JAXB `Marshaller` and `Unmarshaller`.
    `void` | `setBeanClassLoader(ClassLoader classLoader)` Callback that supplies the bean `class loader` to a bean instance.
    `void` | `setCheckForXmlRootElement(boolean checkForXmlRootElement)` Specify whether the `supports(Class)` should check for `@XmlRootElement` annotations.
    `void` | `setClassesToBeBound(Class<?>... classesToBeBound)` Set the list of Java classes to be recognized by a newly created JAXBContext.
    `void` | `setContextPath(String contextPath)` Set a JAXB context path.
    `void` | `setContextPaths(String... contextPaths)` Set multiple JAXB context paths.
    `void` | `setJaxbContextProperties(Map<String,?> jaxbContextProperties)` Set the `JAXBContext` properties.
    `void` | `setLazyInit(boolean lazyInit)` Set whether to lazily initialize the `JAXBContext` for this marshaller.
    `void` | `setMappedClass(Class<?> mappedClass)` Specify a JAXB mapped class for partial unmarshalling.
    `void` | `setMarshallerListener(Marshaller.Listener marshallerListener)` Specify the `Marshaller.Listener` to be registered with the JAXB `Marshaller`.
    `void` | `setMarshallerProperties(Map<String,?> properties)` Set the JAXB `Marshaller` properties.
    `void` | `setMtomEnabled(boolean mtomEnabled)` Specify whether MTOM support should be enabled or not.
    `void` | `setPackagesToScan(String... packagesToScan)` Set the packages to search for classes with JAXB2 annotations in the classpath.
    `void` | `setProcessExternalEntities(boolean processExternalEntities)` Indicate whether external XML entities are processed when unmarshalling.
    `void` | `setSchema(Resource schemaResource)` Set the schema resource to use for validation.
    `void` | `setSchemaLanguage(String schemaLanguage)` Set the schema language.
    `void` | `setSchemaResourceResolver(LSResourceResolver schemaResourceResolver)` Set the resource resolver, as used to load the schema resources.
    `void` | `setSchemas(Resource... schemaResources)` Set the schema resources to use for validation.
    `void` | `setSupportDtd(boolean supportDtd)` Indicate whether DTD parsing should be supported.
    `void` | `setSupportJaxbElementClass(boolean supportJaxbElementClass)` Specify whether the `supports(Class)` returns `true` for the `JAXBElement` class.
    `void` | `setUnmarshallerListener(Unmarshaller.Listener unmarshallerListener)` Set the `Unmarshaller.Listener` to be registered with the JAXB `Unmarshaller`.
    `void` | `setUnmarshallerProperties(Map<String,?> properties)` Set the JAXB `Unmarshaller` properties.
    `void` | `setValidationEventHandler(ValidationEventHandler validationEventHandler)` Set the JAXB validation event handler.
    `boolean` | `supports(Class<?> clazz)` Indicate whether this marshaller can marshal instances of the supplied type.
    `boolean` | `supports(Type genericType)` Indicates whether this marshaller can marshal instances of the supplied generic type.
    `Object` | `unmarshal(Source source)` Unmarshal the given `Source` into an object graph.
    `Object` | `unmarshal(Source source, MimeContainer mimeContainer)` Unmarshals the given provided `Source` into an object graph, reading binary attachments from a `MimeContainer`.
    `protected Object` | `unmarshalStaxSource(Unmarshaller jaxbUnmarshaller, Source staxSource)`

    - ### Methods inherited from class java.lang.Object

      `clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- - ### Field Detail

    - #### logger

          protected final Log logger

      Logger available to subclasses.

  - ### Constructor Detail

    - #### Jaxb2Marshaller

          public Jaxb2Marshaller()

  - ### Method Detail

    - #### setContextPaths

          public void setContextPaths(String... contextPaths)

      Set multiple JAXB context paths. The given array of context paths gets converted to a colon-delimited string, as supported by JAXB.

    - #### setContextPath

          public void setContextPath(@Nullable
                                     String contextPath)

      Set a JAXB context path.

      Setting either this property, `"classesToBeBound"` or `"packagesToScan"` is required.

    - #### getContextPath

          @Nullable
          public String getContextPath()

      Return the JAXB context path.

    - #### setClassesToBeBound

          public void setClassesToBeBound(@Nullable
                                          Class<?>... classesToBeBound)

      Set the list of Java classes to be recognized by a newly created JAXBContext.

      Setting either this property, `"contextPath"` or `"packagesToScan"` is required.

    - #### getClassesToBeBound

          @Nullable
          public Class<?>[] getClassesToBeBound()

      Return the list of Java classes to be recognized by a newly created JAXBContext.

    - #### setPackagesToScan

          public void setPackagesToScan(@Nullable
                                        String... packagesToScan)

      Set the packages to search for classes with JAXB2 annotations in the classpath. This is using a Spring-bases search and therefore analogous to Spring's component-scan feature (`ClassPathBeanDefinitionScanner`).

      Setting either this property, `"contextPath"` or `"classesToBeBound"` is required.

    - #### getPackagesToScan

          @Nullable
          public String[] getPackagesToScan()

      Return the packages to search for JAXB2 annotations.

    - #### setJaxbContextProperties

          public void setJaxbContextProperties(Map<String,?> jaxbContextProperties)

      Set the `JAXBContext` properties. These implementation-specific properties will be set on the underlying `JAXBContext`.

    - #### setMarshallerProperties

          public void setMarshallerProperties(Map<String,?> properties)

      Set the JAXB `Marshaller` properties.

      These properties will be set on the underlying JAXB `Marshaller`, and allow for features such as indentation.

      Parameters:
        `properties` - the properties
      See Also:
        `Marshaller.setProperty(String, Object)`, `Marshaller.JAXB_ENCODING`, `Marshaller.JAXB_FORMATTED_OUTPUT`, `Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION`, `Marshaller.JAXB_SCHEMA_LOCATION`

    - #### setUnmarshallerProperties

          public void setUnmarshallerProperties(Map<String,?> properties)

      Set the JAXB `Unmarshaller` properties.

      These properties will be set on the underlying JAXB `Unmarshaller`.

      Parameters:
        `properties` - the properties
      See Also:
        `Unmarshaller.setProperty(String, Object)`

    - #### setMarshallerListener

          public void setMarshallerListener(Marshaller.Listener marshallerListener)

      Specify the `Marshaller.Listener` to be registered with the JAXB `Marshaller`.

    - #### setUnmarshallerListener

          public void setUnmarshallerListener(Unmarshaller.Listener unmarshallerListener)

      Set the `Unmarshaller.Listener` to be registered with the JAXB `Unmarshaller`.

    - #### setValidationEventHandler

          public void setValidationEventHandler(ValidationEventHandler validationEventHandler)

      Set the JAXB validation event handler. This event handler will be called by JAXB if any validation errors are encountered during calls to any of the marshal APIs.

    - #### setAdapters

          public void setAdapters(XmlAdapter<?,?>... adapters)

      Specify the `XmlAdapter`s to be registered with the JAXB `Marshaller` and `Unmarshaller`.

    - #### setSchema

          public void setSchema(Resource schemaResource)

      Set the schema resource to use for validation.

    - #### setSchemas

          public void setSchemas(Resource... schemaResources)

      Set the schema resources to use for validation.

    - #### setSchemaLanguage

          public void setSchemaLanguage(String schemaLanguage)

      Set the schema language. Default is the W3C XML Schema: `http://www.w3.org/2001/XMLSchema"`.
      See Also:
        `XMLConstants.W3C_XML_SCHEMA_NS_URI`, `XMLConstants.RELAXNG_NS_URI`

    - #### setSchemaResourceResolver

          public void setSchemaResourceResolver(LSResourceResolver schemaResourceResolver)

      Set the resource resolver, as used to load the schema resources.
      See Also:
        `SchemaFactory.setResourceResolver(org.w3c.dom.ls.LSResourceResolver)`, `setSchema(org.springframework.core.io.Resource)`, `setSchemas(org.springframework.core.io.Resource...)`

    - #### setLazyInit

          public void setLazyInit(boolean lazyInit)

      Set whether to lazily initialize the `JAXBContext` for this marshaller. Default is `false` to initialize on startup; can be switched to `true`.

      Early initialization just applies if `afterPropertiesSet()` is called.

    - #### setMtomEnabled

          public void setMtomEnabled(boolean mtomEnabled)

      Specify whether MTOM support should be enabled or not. Default is `false`: marshalling using XOP/MTOM not being enabled.

    - #### setSupportJaxbElementClass

          public void setSupportJaxbElementClass(boolean supportJaxbElementClass)

      Specify whether the `supports(Class)` returns `true` for the `JAXBElement` class.

      Default is `false`, meaning that `supports(Class)` always returns `false` for `JAXBElement` classes (though `supports(Type)` can return `true`, since it can obtain the type parameters of `JAXBElement`).

      This property is typically enabled in combination with usage of classes like `MarshallingView`, since the `ModelAndView` does not offer type parameter information at runtime.

      See Also:
        `supports(Class)`, `supports(Type)`

    - #### setCheckForXmlRootElement

          public void setCheckForXmlRootElement(boolean checkForXmlRootElement)

      Specify whether the `supports(Class)` should check for `@XmlRootElement` annotations.

      Default is `true`, meaning that `supports(Class)` will check for this annotation. However, some JAXB implementations (i.e. EclipseLink MOXy) allow for defining the bindings in an external definition file, thus keeping the classes annotations free. Setting this property to `false` supports these JAXB implementations.

      See Also:
        `supports(Class)`, `supports(Type)`

    - #### setMappedClass

          public void setMappedClass(Class<?> mappedClass)

      Specify a JAXB mapped class for partial unmarshalling.
      See Also:
        `Unmarshaller.unmarshal(javax.xml.transform.Source, Class)`

    - #### setSupportDtd

          public void setSupportDtd(boolean supportDtd)

      Indicate whether DTD parsing should be supported.

      Default is `false` meaning that DTD is disabled.

    - #### isSupportDtd

          public boolean isSupportDtd()

      Return whether DTD parsing is supported.

    - #### setProcessExternalEntities

          public void setProcessExternalEntities(boolean processExternalEntities)

      Indicate whether external XML entities are processed when unmarshalling.

      Default is `false`, meaning that external entities are not resolved. Note that processing of external entities will only be enabled/disabled when the `Source` passed to `unmarshal(Source)` is a `SAXSource` or `StreamSource`. It has no effect for `DOMSource` or `StAXSource` instances.

      Note: setting this option to `true` also automatically sets `setSupportDtd(boolean)` to `true`.

    - #### isProcessExternalEntities

          public boolean isProcessExternalEntities()

      Return whether XML external entities are allowed.

    - #### setBeanClassLoader

          public void setBeanClassLoader(ClassLoader classLoader)

      Description copied from interface: `BeanClassLoaderAware`
      Callback that supplies the bean `class 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.

      Specified by:
        `setBeanClassLoader` in interface `BeanClassLoaderAware`
      Parameters:
        `classLoader` - the owning class loader

    - #### afterPropertiesSet

          public void afterPropertiesSet()
                                  throws Exception

      Description copied from interface: `InitializingBean`
      Invoked by the containing `BeanFactory` after it has set all bean properties and satisfied `BeanFactoryAware`, `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.

      Specified by:
        `afterPropertiesSet` in interface `InitializingBean`
      Throws:
        `Exception` - in the event of misconfiguration (such as failure to set an essential property) or if initialization fails for any other reason

    - #### getJaxbContext

          public JAXBContext getJaxbContext()

      Return the JAXBContext used by this marshaller, lazily building it if necessary.

    - #### supports

          public boolean supports(Class<?> clazz)

      Description copied from interface: `Marshaller`
      Indicate whether this marshaller can marshal instances of the supplied type.
      Specified by:
        `supports` in interface `Marshaller`
      Specified by:
        `supports` in interface `Unmarshaller`
      Parameters:
        `clazz` - the class that this marshaller is being asked if it can marshal
      Returns:
        `true` if this marshaller can indeed marshal instances of the supplied class; `false` otherwise

    - #### supports

          public boolean supports(Type genericType)

      Description copied from interface: `GenericMarshaller`
      Indicates whether this marshaller can marshal instances of the supplied generic type.
      Specified by:
        `supports` in interface `GenericMarshaller`
      Specified by:
        `supports` in interface `GenericUnmarshaller`
      Parameters:
        `genericType` - the type that this marshaller is being asked if it can marshal
      Returns:
        `true` if this marshaller can indeed marshal instances of the supplied type; `false` otherwise

    - #### marshal

          public void marshal(Object graph,
                              Result result)
                       throws XmlMappingException

      Description copied from interface: `Marshaller`
      Marshal the object graph with the given root into the provided `Result`.
      Specified by:
        `marshal` in interface `Marshaller`
      Parameters:
        `graph` - the root of the object graph to marshal
        `result` - the result to marshal to
      Throws:
        `XmlMappingException` - if the given object cannot be marshalled to the result

    - #### marshal

          public void marshal(Object graph,
                              Result result,
                              @Nullable
                              MimeContainer mimeContainer)
                       throws XmlMappingException

      Description copied from interface: `MimeMarshaller`
      Marshals the object graph with the given root into the provided `Result`, writing binary data to a `MimeContainer`.
      Specified by:
        `marshal` in interface `MimeMarshaller`
      Parameters:
        `graph` - the root of the object graph to marshal
        `result` - the result to marshal to
        `mimeContainer` - the MIME container to write extracted binary content to
      Throws:
        `XmlMappingException` - if the given object cannot be marshalled to the result

    - #### createMarshaller

          public Marshaller createMarshaller()

      Return a newly created JAXB marshaller.

      Note: JAXB marshallers are not necessarily thread-safe. This method is public as of 5.2.

      Since:
        5.2
      See Also:
        `createUnmarshaller()`

    - #### initJaxbMarshaller

          protected void initJaxbMarshaller(Marshaller marshaller)
                                     throws JAXBException

      Template method that can be overridden by concrete JAXB marshallers for custom initialization behavior. Gets called after creation of JAXB `Marshaller`, and after the respective properties have been set.

      The default implementation sets the `defined properties`, the `validation event handler`, the `schemas`, `listener`, and `adapters`.

      Throws:
        `JAXBException`

    - #### unmarshal

          public Object unmarshal(Source source)
                           throws XmlMappingException

      Description copied from interface: `Unmarshaller`
      Unmarshal the given `Source` into an object graph.
      Specified by:
        `unmarshal` in interface `Unmarshaller`
      Parameters:
        `source` - the source to marshal from
      Returns:
        the object graph
      Throws:
        `XmlMappingException` - if the given source cannot be mapped to an object

    - #### unmarshal

          public Object unmarshal(Source source,
                                  @Nullable
                                  MimeContainer mimeContainer)
                           throws XmlMappingException

      Description copied from interface: `MimeUnmarshaller`
      Unmarshals the given provided `Source` into an object graph, reading binary attachments from a `MimeContainer`.
      Specified by:
        `unmarshal` in interface `MimeUnmarshaller`
      Parameters:
        `source` - the source to marshal from
        `mimeContainer` - the MIME container to read extracted binary content from
      Returns:
        the object graph
      Throws:
        `XmlMappingException` - if the given source cannot be mapped to an object

    - #### createUnmarshaller

          public Unmarshaller createUnmarshaller()

      Return a newly created JAXB unmarshaller.

      Note: JAXB unmarshallers are not necessarily thread-safe. This method is public as of 5.2.

      Since:
        5.2
      See Also:
        `createMarshaller()`

    - #### unmarshalStaxSource

          protected Object unmarshalStaxSource(Unmarshaller jaxbUnmarshaller,
                                               Source staxSource)
                                        throws JAXBException

      Throws:
        `JAXBException`

    - #### initJaxbUnmarshaller

          protected void initJaxbUnmarshaller(Unmarshaller unmarshaller)
                                       throws JAXBException

      Template method that can be overridden by concrete JAXB marshallers for custom initialization behavior. Gets called after creation of JAXB `Marshaller`, and after the respective properties have been set.

      The default implementation sets the `defined properties`, the `validation event handler`, the `schemas`, `listener`, and `adapters`.

      Throws:
        `JAXBException`

    - #### convertJaxbException

          protected XmlMappingException convertJaxbException(JAXBException ex)

      Convert the given `JAXBException` to an appropriate exception from the `org.springframework.oxm` hierarchy.
      Parameters:
        `ex` - `JAXBException` that occurred
      Returns:
        the corresponding `XmlMappingException`