5.3. JAXB
JAXB 支持通过 Camel JAXB 数据格式 提供。
Camel 支持 unmarshalling XML 数据到 JAXB 注解的类,以及从类到 XML 的 marshalling。以下演示了一个简单的 Camel 路由,用于处理 Camel JAXB 数据格式类的 marshalling 和 unmarshalling。
5.3.1. JAXB Annotated 类
@XmlRootElement(name = "customer")
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer implements Serializable {
private String firstName;
private String lastName;
public Customer() {
}
public Customer(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}5.3.2. JAXB 类 XML 表示
<customer xmlns="http://org/wildfly/test/jaxb/model/Customer">
<firstName>John</firstName>
<lastName>Doe</lastName>
</customer>5.3.3. Camel JAXB Unmarshalling
WildFlyCamelContext camelctx = contextFactory.createCamelContext(getClass().getClassLoader());
final JaxbDataFormat jaxb = new JaxbDataFormat();
jaxb.setContextPath("org.wildfly.camel.test.jaxb.model");
camelctx.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start")
.unmarshal(jaxb);
}
});
camelctx.start();
ProducerTemplate producer = camelctx.createProducerTemplate();
// Send an XML representation of the customer to the direct:start endpoint
Customer customer = producer.requestBody("direct:start", readCustomerXml(), Customer.class);
Assert.assertEquals("John", customer.getFirstName());
Assert.assertEquals("Doe", customer.getLastName());5.3.4. Camel JAXB Marshalling
WildFlyCamelContext camelctx = contextFactory.createCamelContext();
final JaxbDataFormat jaxb = new JaxbDataFormat();
jaxb.setContextPath("org.wildfly.camel.test.jaxb.model");
camelctx.addRoutes(new RouteBuilder() {
@Override
public void configure() throws Exception {
from("direct:start")
.marshal(jaxb);
}
});
camelctx.start();
ProducerTemplate producer = camelctx.createProducerTemplate();
Customer customer = new Customer("John", "Doe");
String customerXML = producer.requestBody("direct:start", customer, String.class);
Assert.assertEquals(readCustomerXml(), customerXML);