0
# JAXB Implementation
1
2
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.
3
4
## Core Class
5
6
### Jaxb2Marshaller
7
8
The main JAXB implementation class that provides complete marshalling and unmarshalling functionality.
9
10
```java { .api }
11
public class Jaxb2Marshaller implements GenericMarshaller, GenericUnmarshaller,
12
MimeMarshaller, MimeUnmarshaller,
13
BeanClassLoaderAware, InitializingBean {
14
15
// Configuration Methods
16
public void setClassesToBeBound(Class<?>... classesToBeBound);
17
public void setContextPaths(String... contextPaths);
18
public void setPackagesToScan(String... packagesToScan);
19
public void setSchema(Resource schemaResource);
20
public void setSchemas(Resource... schemaResources);
21
public void setValidationEventHandler(ValidationEventHandler validationEventHandler);
22
public void setMarshallerProperties(Map<String, ?> properties);
23
public void setUnmarshallerProperties(Map<String, ?> properties);
24
public void setAdapters(XmlAdapter<?, ?>... adapters);
25
public void setSupportDtd(boolean supportDtd);
26
public void setSupportExternalEntities(boolean supportExternalEntities);
27
public void setProcessExternalEntities(boolean processExternalEntities);
28
public void setMtomEnabled(boolean mtomEnabled);
29
public void setAttachmentMarshaller(AttachmentMarshaller attachmentMarshaller);
30
public void setAttachmentUnmarshaller(AttachmentUnmarshaller attachmentUnmarshaller);
31
public void setMarshallerListener(Marshaller.Listener marshallerListener);
32
public void setUnmarshallerListener(Unmarshaller.Listener unmarshallerListener);
33
public void setEntityResolver(EntityResolver entityResolver);
34
public void setLazyInit(boolean lazyInit);
35
36
// Inherited from interfaces
37
public boolean supports(Class<?> clazz);
38
public boolean supports(Type genericType);
39
public void marshal(Object graph, Result result) throws IOException, XmlMappingException;
40
public void marshal(Object graph, Result result, MimeContainer mimeContainer)
41
throws XmlMappingException, IOException;
42
public Object unmarshal(Source source) throws IOException, XmlMappingException;
43
public Object unmarshal(Source source, MimeContainer mimeContainer)
44
throws XmlMappingException, IOException;
45
}
46
```
47
48
## Configuration Options
49
50
### Class Binding
51
52
Configure which classes the marshaller should handle:
53
54
```java
55
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
56
57
// Option 1: Specify classes directly
58
marshaller.setClassesToBeBound(Customer.class, Order.class, Product.class);
59
60
// Option 2: Use context paths (package names)
61
marshaller.setContextPaths("com.example.model", "com.example.dto");
62
63
// Option 3: Scan packages for JAXB annotations
64
marshaller.setPackagesToScan("com.example");
65
66
marshaller.afterPropertiesSet();
67
```
68
69
### Schema Validation
70
71
Enable XML schema validation during marshalling/unmarshalling:
72
73
```java
74
import org.springframework.core.io.ClassPathResource;
75
76
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
77
marshaller.setClassesToBeBound(MyClass.class);
78
79
// Single schema
80
marshaller.setSchema(new ClassPathResource("schema.xsd"));
81
82
// Multiple schemas
83
marshaller.setSchemas(
84
new ClassPathResource("schema1.xsd"),
85
new ClassPathResource("schema2.xsd")
86
);
87
88
// Custom validation event handler
89
marshaller.setValidationEventHandler(event -> {
90
System.err.println("Validation error: " + event.getMessage());
91
return true; // Continue processing
92
});
93
94
marshaller.afterPropertiesSet();
95
```
96
97
### JAXB Properties
98
99
Configure JAXB marshaller and unmarshaller properties:
100
101
```java
102
import jakarta.xml.bind.Marshaller;
103
import java.util.HashMap;
104
import java.util.Map;
105
106
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
107
marshaller.setClassesToBeBound(MyClass.class);
108
109
// Marshaller properties
110
Map<String, Object> marshallerProps = new HashMap<>();
111
marshallerProps.put(Marshaller.JAXB_FORMATTED_OUTPUT, true);
112
marshallerProps.put(Marshaller.JAXB_ENCODING, "UTF-8");
113
marshallerProps.put(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, "schema.xsd");
114
marshaller.setMarshallerProperties(marshallerProps);
115
116
// Unmarshaller properties
117
Map<String, Object> unmarshallerProps = new HashMap<>();
118
// Add unmarshaller-specific properties
119
marshaller.setUnmarshallerProperties(unmarshallerProps);
120
121
marshaller.afterPropertiesSet();
122
```
123
124
### XML Adapters
125
126
Use custom XML adapters for complex type conversions:
127
128
```java
129
import jakarta.xml.bind.annotation.adapters.XmlAdapter;
130
131
// Custom adapter for date formatting
132
public class DateAdapter extends XmlAdapter<String, Date> {
133
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
134
135
@Override
136
public Date unmarshal(String v) throws Exception {
137
return dateFormat.parse(v);
138
}
139
140
@Override
141
public String marshal(Date v) throws Exception {
142
return dateFormat.format(v);
143
}
144
}
145
146
// Configure marshaller with adapter
147
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
148
marshaller.setClassesToBeBound(MyClass.class);
149
marshaller.setAdapters(new DateAdapter(), new MyCustomAdapter());
150
marshaller.afterPropertiesSet();
151
```
152
153
### Security Configuration
154
155
Configure security settings for XML processing:
156
157
```java
158
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
159
marshaller.setClassesToBeBound(MyClass.class);
160
161
// Disable DTD processing for security
162
marshaller.setSupportDtd(false);
163
164
// Disable external entity processing
165
marshaller.setSupportExternalEntities(false);
166
marshaller.setProcessExternalEntities(false);
167
168
marshaller.afterPropertiesSet();
169
```
170
171
## Usage Examples
172
173
### Basic Usage
174
175
```java
176
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
177
import javax.xml.transform.stream.StreamResult;
178
import javax.xml.transform.stream.StreamSource;
179
import java.io.StringWriter;
180
import java.io.StringReader;
181
182
// Configure marshaller
183
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
184
marshaller.setClassesToBeBound(Customer.class);
185
marshaller.afterPropertiesSet();
186
187
// Marshal object to XML
188
Customer customer = new Customer("John", "Doe");
189
StringWriter writer = new StringWriter();
190
marshaller.marshal(customer, new StreamResult(writer));
191
String xml = writer.toString();
192
193
// Unmarshal XML to object
194
StringReader reader = new StringReader(xml);
195
Customer unmarshalled = (Customer) marshaller.unmarshal(new StreamSource(reader));
196
```
197
198
### With Validation
199
200
```java
201
import jakarta.xml.bind.ValidationEventHandler;
202
import jakarta.xml.bind.ValidationEvent;
203
204
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
205
marshaller.setClassesToBeBound(Customer.class);
206
marshaller.setSchema(new ClassPathResource("customer.xsd"));
207
208
// Custom validation handler
209
marshaller.setValidationEventHandler(new ValidationEventHandler() {
210
@Override
211
public boolean handleEvent(ValidationEvent event) {
212
System.err.println("Validation error: " + event.getMessage());
213
System.err.println("Location: " + event.getLocator().getLineNumber() +
214
":" + event.getLocator().getColumnNumber());
215
return false; // Stop on validation error
216
}
217
});
218
219
marshaller.afterPropertiesSet();
220
221
try {
222
Customer customer = new Customer();
223
StringWriter writer = new StringWriter();
224
marshaller.marshal(customer, new StreamResult(writer));
225
} catch (ValidationFailureException e) {
226
System.err.println("Validation failed: " + e.getMessage());
227
}
228
```
229
230
### MIME Attachments
231
232
```java
233
import org.springframework.oxm.mime.MimeContainer;
234
import jakarta.activation.DataHandler;
235
import jakarta.activation.ByteArrayDataSource;
236
237
// Assuming you have a MimeContainer implementation
238
MimeContainer mimeContainer = // ... get mime container
239
240
// Marshal with MIME attachments
241
Customer customer = new Customer();
242
customer.setPhoto(new byte[]{ /* image data */ });
243
244
StringWriter writer = new StringWriter();
245
marshaller.marshal(customer, new StreamResult(writer), mimeContainer);
246
247
// The binary data will be stored as MIME attachment
248
// XML will contain reference to the attachment
249
```
250
251
## Helper Classes
252
253
### ClassPathJaxb2TypeScanner
254
255
Utility for scanning packages for JAXB-annotated classes:
256
257
```java { .api }
258
public class ClassPathJaxb2TypeScanner {
259
public ClassPathJaxb2TypeScanner(ClassLoader classLoader, String... packagesToScan);
260
public Class<?>[] scanPackages() throws IOException, ClassNotFoundException;
261
}
262
```
263
264
Usage example:
265
266
```java
267
import org.springframework.oxm.jaxb.ClassPathJaxb2TypeScanner;
268
269
// Scan packages for JAXB classes
270
ClassPathJaxb2TypeScanner scanner = new ClassPathJaxb2TypeScanner(
271
Thread.currentThread().getContextClassLoader(),
272
"com.example.model",
273
"com.example.dto"
274
);
275
276
Class<?>[] classes = scanner.scanPackages();
277
278
// Use scanned classes with marshaller
279
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
280
marshaller.setClassesToBeBound(classes);
281
marshaller.afterPropertiesSet();
282
```
283
284
## Required Imports
285
286
```java
287
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
288
import org.springframework.oxm.jaxb.ClassPathJaxb2TypeScanner;
289
import org.springframework.oxm.ValidationFailureException;
290
import org.springframework.oxm.mime.MimeContainer;
291
import org.springframework.core.io.Resource;
292
import org.springframework.core.io.ClassPathResource;
293
294
import jakarta.xml.bind.ValidationEventHandler;
295
import jakarta.xml.bind.ValidationEvent;
296
import jakarta.xml.bind.annotation.adapters.XmlAdapter;
297
import jakarta.xml.bind.attachment.AttachmentMarshaller;
298
import jakarta.xml.bind.attachment.AttachmentUnmarshaller;
299
import jakarta.xml.bind.Marshaller;
300
import jakarta.xml.bind.Unmarshaller;
301
302
import javax.xml.transform.stream.StreamResult;
303
import javax.xml.transform.stream.StreamSource;
304
import java.util.Map;
305
import java.util.HashMap;
306
```
307
308
## Common Configuration Patterns
309
310
### Spring Bean Configuration
311
312
```xml
313
<bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
314
<property name="classesToBeBound">
315
<list>
316
<value>com.example.Customer</value>
317
<value>com.example.Order</value>
318
</list>
319
</property>
320
<property name="schema" value="classpath:schema.xsd"/>
321
<property name="validationEventHandler" ref="validationHandler"/>
322
</bean>
323
```
324
325
### Java Configuration
326
327
```java
328
@Configuration
329
public class MarshallingConfig {
330
331
@Bean
332
public Jaxb2Marshaller jaxb2Marshaller() {
333
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
334
marshaller.setClassesToBeBound(Customer.class, Order.class);
335
marshaller.setSchema(new ClassPathResource("schema.xsd"));
336
return marshaller;
337
}
338
}
339
```