Spring Object/XML Marshalling support providing generic interfaces for converting Java objects to XML and vice versa
The JAXB implementation provides comprehensive XML marshalling and unmarshalling using Jakarta XML Binding (JAXB). It supports validation, schema handling, MIME attachments, and various configuration options for enterprise XML processing.
The main JAXB implementation class that provides complete marshalling and unmarshalling functionality.
public class Jaxb2Marshaller implements GenericMarshaller, GenericUnmarshaller,
MimeMarshaller, MimeUnmarshaller,
BeanClassLoaderAware, InitializingBean {
// Configuration Methods
public void setClassesToBeBound(Class<?>... classesToBeBound);
public void setContextPaths(String... contextPaths);
public void setPackagesToScan(String... packagesToScan);
public void setSchema(Resource schemaResource);
public void setSchemas(Resource... schemaResources);
public void setValidationEventHandler(ValidationEventHandler validationEventHandler);
public void setMarshallerProperties(Map<String, ?> properties);
public void setUnmarshallerProperties(Map<String, ?> properties);
public void setAdapters(XmlAdapter<?, ?>... adapters);
public void setSupportDtd(boolean supportDtd);
public void setSupportExternalEntities(boolean supportExternalEntities);
public void setProcessExternalEntities(boolean processExternalEntities);
public void setMtomEnabled(boolean mtomEnabled);
public void setAttachmentMarshaller(AttachmentMarshaller attachmentMarshaller);
public void setAttachmentUnmarshaller(AttachmentUnmarshaller attachmentUnmarshaller);
public void setMarshallerListener(Marshaller.Listener marshallerListener);
public void setUnmarshallerListener(Unmarshaller.Listener unmarshallerListener);
public void setEntityResolver(EntityResolver entityResolver);
public void setLazyInit(boolean lazyInit);
// Inherited from interfaces
public boolean supports(Class<?> clazz);
public boolean supports(Type genericType);
public void marshal(Object graph, Result result) throws IOException, XmlMappingException;
public void marshal(Object graph, Result result, MimeContainer mimeContainer)
throws XmlMappingException, IOException;
public Object unmarshal(Source source) throws IOException, XmlMappingException;
public Object unmarshal(Source source, MimeContainer mimeContainer)
throws XmlMappingException, IOException;
}Configure which classes the marshaller should handle:
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
// Option 1: Specify classes directly
marshaller.setClassesToBeBound(Customer.class, Order.class, Product.class);
// Option 2: Use context paths (package names)
marshaller.setContextPaths("com.example.model", "com.example.dto");
// Option 3: Scan packages for JAXB annotations
marshaller.setPackagesToScan("com.example");
marshaller.afterPropertiesSet();Enable XML schema validation during marshalling/unmarshalling:
import org.springframework.core.io.ClassPathResource;
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(MyClass.class);
// Single schema
marshaller.setSchema(new ClassPathResource("schema.xsd"));
// Multiple schemas
marshaller.setSchemas(
new ClassPathResource("schema1.xsd"),
new ClassPathResource("schema2.xsd")
);
// Custom validation event handler
marshaller.setValidationEventHandler(event -> {
System.err.println("Validation error: " + event.getMessage());
return true; // Continue processing
});
marshaller.afterPropertiesSet();Configure JAXB marshaller and unmarshaller properties:
import jakarta.xml.bind.Marshaller;
import java.util.HashMap;
import java.util.Map;
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(MyClass.class);
// Marshaller properties
Map<String, Object> marshallerProps = new HashMap<>();
marshallerProps.put(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshallerProps.put(Marshaller.JAXB_ENCODING, "UTF-8");
marshallerProps.put(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "schema.xsd");
marshaller.setMarshallerProperties(marshallerProps);
// Unmarshaller properties
Map<String, Object> unmarshallerProps = new HashMap<>();
// Add unmarshaller-specific properties
marshaller.setUnmarshallerProperties(unmarshallerProps);
marshaller.afterPropertiesSet();Use custom XML adapters for complex type conversions:
import jakarta.xml.bind.annotation.adapters.XmlAdapter;
// Custom adapter for date formatting
public class DateAdapter extends XmlAdapter<String, Date> {
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
@Override
public Date unmarshal(String v) throws Exception {
return dateFormat.parse(v);
}
@Override
public String marshal(Date v) throws Exception {
return dateFormat.format(v);
}
}
// Configure marshaller with adapter
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(MyClass.class);
marshaller.setAdapters(new DateAdapter(), new MyCustomAdapter());
marshaller.afterPropertiesSet();Configure security settings for XML processing:
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(MyClass.class);
// Disable DTD processing for security
marshaller.setSupportDtd(false);
// Disable external entity processing
marshaller.setSupportExternalEntities(false);
marshaller.setProcessExternalEntities(false);
marshaller.afterPropertiesSet();import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.StringWriter;
import java.io.StringReader;
// Configure marshaller
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(Customer.class);
marshaller.afterPropertiesSet();
// Marshal object to XML
Customer customer = new Customer("John", "Doe");
StringWriter writer = new StringWriter();
marshaller.marshal(customer, new StreamResult(writer));
String xml = writer.toString();
// Unmarshal XML to object
StringReader reader = new StringReader(xml);
Customer unmarshalled = (Customer) marshaller.unmarshal(new StreamSource(reader));import jakarta.xml.bind.ValidationEventHandler;
import jakarta.xml.bind.ValidationEvent;
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(Customer.class);
marshaller.setSchema(new ClassPathResource("customer.xsd"));
// Custom validation handler
marshaller.setValidationEventHandler(new ValidationEventHandler() {
@Override
public boolean handleEvent(ValidationEvent event) {
System.err.println("Validation error: " + event.getMessage());
System.err.println("Location: " + event.getLocator().getLineNumber() +
":" + event.getLocator().getColumnNumber());
return false; // Stop on validation error
}
});
marshaller.afterPropertiesSet();
try {
Customer customer = new Customer();
StringWriter writer = new StringWriter();
marshaller.marshal(customer, new StreamResult(writer));
} catch (ValidationFailureException e) {
System.err.println("Validation failed: " + e.getMessage());
}import org.springframework.oxm.mime.MimeContainer;
import jakarta.activation.DataHandler;
import jakarta.activation.ByteArrayDataSource;
// Assuming you have a MimeContainer implementation
MimeContainer mimeContainer = // ... get mime container
// Marshal with MIME attachments
Customer customer = new Customer();
customer.setPhoto(new byte[]{ /* image data */ });
StringWriter writer = new StringWriter();
marshaller.marshal(customer, new StreamResult(writer), mimeContainer);
// The binary data will be stored as MIME attachment
// XML will contain reference to the attachmentUtility for scanning packages for JAXB-annotated classes:
public class ClassPathJaxb2TypeScanner {
public ClassPathJaxb2TypeScanner(ClassLoader classLoader, String... packagesToScan);
public Class<?>[] scanPackages() throws IOException, ClassNotFoundException;
}Usage example:
import org.springframework.oxm.jaxb.ClassPathJaxb2TypeScanner;
// Scan packages for JAXB classes
ClassPathJaxb2TypeScanner scanner = new ClassPathJaxb2TypeScanner(
Thread.currentThread().getContextClassLoader(),
"com.example.model",
"com.example.dto"
);
Class<?>[] classes = scanner.scanPackages();
// Use scanned classes with marshaller
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(classes);
marshaller.afterPropertiesSet();import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.oxm.jaxb.ClassPathJaxb2TypeScanner;
import org.springframework.oxm.ValidationFailureException;
import org.springframework.oxm.mime.MimeContainer;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ClassPathResource;
import jakarta.xml.bind.ValidationEventHandler;
import jakarta.xml.bind.ValidationEvent;
import jakarta.xml.bind.annotation.adapters.XmlAdapter;
import jakarta.xml.bind.attachment.AttachmentMarshaller;
import jakarta.xml.bind.attachment.AttachmentUnmarshaller;
import jakarta.xml.bind.Marshaller;
import jakarta.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.util.Map;
import java.util.HashMap;<bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>com.example.Customer</value>
<value>com.example.Order</value>
</list>
</property>
<property name="schema" value="classpath:schema.xsd"/>
<property name="validationEventHandler" ref="validationHandler"/>
</bean>@Configuration
public class MarshallingConfig {
@Bean
public Jaxb2Marshaller jaxb2Marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(Customer.class, Order.class);
marshaller.setSchema(new ClassPathResource("schema.xsd"));
return marshaller;
}
}Install with Tessl CLI
npx tessl i tessl/maven-org-springframework--spring-oxm