April 11, 2011

MOXy's XML Metadata in a JAX-RS Service

In previous posts I introduced how EclipseLink JAXB (MOXy) can represent it's metadata as XML, and how MOXy can be used in a JAX-RS service.  In this post I'll demonstrate how to leverage MOXy's metadata file in a JAX-RS service by using a ContextResolver.


By default a JAX-RS implementation will bootstrap a JAXBContext from the parameters or return type from a service method. You can control how the JAXBContext is created through the ContextResolver mechanism. The ContextResolver allows you to control what JAXBContext is used with a particular class. In this example we tell the JAX-RS implementation to use a MOXy JAXBContext in which the metadata has been supplied via XML:

package org.example;

import java.util.*;
import javax.ws.rs.Produces;
import javax.ws.rs.ext.*;
import javax.xml.bind.*;
import org.eclipse.persistence.jaxb.JAXBContextFactory;

@Produces({"application/xml", "application/json"})
public class CustomerContextResolver implements ContextResolver<JAXBContext> {

    private JAXBContext jc;

    public CustomerContextResolver() {
        try {
            Map<String, Object> props = new HashMap<String, Object>(1);
            props.put(JAXBContextFactory.ECLIPSELINK_OXM_XML_KEY, "org/example/binding.xml");
            jc = JAXBContext.newInstance(new Class[] {Customer.class} , props);
        } catch(JAXBException e) {
            throw new RuntimeException(e);

    public JAXBContext getContext(Class<?> clazz) {
        if(Customer.class == clazz) {
            return jc;
        return null;



Below is the external mapping document we will use for this example.  For more information on MOXy's external mapping document see:  Extending JAXB - Representing Metadata as XML.
<?xml version="1.0"?>
        <java-type name="Customer">
            <xml-type prop-order="firstName lastName address phoneNumbers"/>
                <xml-attribute java-attribute="id"/>
                <xml-element java-attribute="firstName" name="first-name"/>
                <xml-element java-attribute="lastName" name="last-name"/>
                <xml-element java-attribute="phoneNumbers" name="phone-number"/>
        <java-type name="Address">
                <xml-attribute java-attribute="id"/>
        <java-type name="PhoneNumber">
                <xml-attribute java-attribute="id"/>
                <xml-attribute java-attribute="type"/>
                <xml-value java-attribute="num"/>

Further Reading

If you enjoyed this post then you may also be interested in:

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.