When an instance of a class is used with a Web Service, the JAX-WS implementation can choose to handle fields/properties that hold binary data as SOAP attachment. An attachment is a means to send the data outside of the XML message, this is done as an optimization since binary data encoded as a xs:base64Binary string could be quite large. JAXB offers a couple of annotations to control this behaviour:

* @XmlInlineBinaryData
This specifies that the binary data for this field/property must be written to the XML document as xs:base64Binary and not sent as an attachment.
* @XmlMimeType
For properties of type java.awt.Image or javax.xml.transform.Source, this annotation allows the mime type to be specified that will be used for encoding the data as bytes.

Java Model

The following class will be used as the domain model for this example. It has various properties for representing binary data. Property "c" has been annotated with @XmlInlineBinaryData to prevent that data from being treated as an attachment, and property "d" has been annotated with @XmlMimeType to specify that the Image should be encoded as a JPEG.

Web Service Layer

When a JAX-WS implementation leverages attachments the XML payload will look similar to the following. Some data will be marshalled as xs:base64Binary and other data will be marshalled as an identifier that will serve as a reference to the attachment.

A JAX-WS provider achieves this by leveraging JAXB's AttachmentMarshaller and AttachmentUnmarshaller mechanisms. You do not need to write any code to make this happen. The following code is provided to give you a behind the scenes look.

Example AttachmentMarshaller

A JAX-WS provider that wants to leverage attachments registers an implementation of javax.xml.bind.attachment.AttachmentMarshaller on the JAXB Marshaller. The implementation is specific to the JAX-WS provider, but below is a sample of how it might look. A JAX-WS provider can choose when to handle binary data as an attachment, in the implementation below any candidate byte[] of size greater than 10 will be treated as an attachment.

Example AttachmentUnmarshaller

If a JAX-WS provider is leveraging attachments, then an implementation of javax.xml.bind.attachment.AttachmentUnmarshaller must be specified on the JAXB Unmarshaller. Again the implementations is specific to the JAX-WS provider. A sample implementation is shown below:

Demo Code

The following example was inspired by an answer I gave on Stack Overflow (feel free to up vote). It covers how to leverage JAXB's AttachmentMarshaller & AttachmentUnmarshaller to produce a message in the following format: