質問

I have worked with Jax WS and had used wsgen and wsimport for auto marshalling of custom types. Can I use wsgen with JaxRS as well? If so where should I place my wsgen generated files and how to reference them? I just wish not to deal with using JAXB myself and use wsgen as a shortcut.

役に立ちましたか?

解決

By default a JAX-RS implementation will use JAXB to convert domain objects to/from XML for the application/xml media type. In the example below a JAXBContext will be created on the Customer class since it appears as a parameter and/or return type in the RESTful operations.

package org.example;

import java.util.List;

import javax.ejb.*;
import javax.persistence.*;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;

@Stateless
@LocalBean
@Path("/customers")
public class CustomerService {

    @PersistenceContext(unitName="CustomerService",
                        type=PersistenceContextType.TRANSACTION)
    EntityManager entityManager;

    @POST
    @Consumes(MediaType.APPLICATION_XML)
    public void create(Customer customer) {
        entityManager.persist(customer);
    }

    @GET
    @Produces(MediaType.APPLICATION_XML)
    @Path("{id}")
    public Customer read(@PathParam("id") long id) {
        return entityManager.find(Customer.class, id);
    }

}

The JAXBContext created on a single class will also create metadata for all transitively reference classes but that may not bring in everything that was generated from your XML schema. You will need to leverage the JAX-RS context resolver mechanism.

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;

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

    private JAXBContext jc;

    public CustomerContextResolver() {
        try {
            jc = JAXBContext.newInstance("com.example.customer" , Customer.class.getClassLoader());
        } catch(JAXBException e) {
            throw new RuntimeException(e);
        }
    }

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

}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top