私は Jax WS を使用しており、カスタム型の自動マーシャリングに wsgen と wsimport を使用していました。JaxRS でも wsgen を使用できますか? その場合、wsgen で生成されたファイルをどこに配置し、それらを参照する方法を教えてください。自分で JAXB を使用するのではなく、wsgen をショートカットとして使用したいだけです。
質問する
419 次
1 に答える
1
デフォルトでは、JAX-RS 実装は JAXB を使用して、ドメイン オブジェクトをapplication/xml
メディア タイプの XML との間で変換します。以下の例でJAXBContext
は、クラスに が作成されCustomer
ます。これは、RESTful 操作でパラメーターおよび/または戻り値の型として表示されるためです。
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);
}
}
単一のJAXBContext
クラスで作成された は、推移的に参照するすべてのクラスのメタデータも作成しますが、XML スキーマから生成されたすべてのものを取り込めない場合があります。JAX-RS コンテキスト リゾルバー メカニズムを活用する必要があります。
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;
}
}
于 2012-10-29T14:46:17.297 に答える