我有一个 XmlAdapter 来将类中的关联对象编码到它们各自的 REST URI:
public class AirportAdapter extends XmlAdapter<URI, Airport> {
@Override
public URI marshal(Airport airport) throws Exception {
return UriBuilder.fromResource(AirportsResource.class).path(AirportsResource.class,
"getAirportResource").build(airport.getId());
}
然而,这会产生一个相对 URL (/airports/1),它无法将 URI 解码到 Airport
对象中(显然):
@Override
public Airport unmarshal(URI uri) throws Exception {
// Does work, but not desirable
return JAXB.unmarshal("http://localhost/resources" + uri, Airport.class)
// Does not work
return JAXB.unmarshal(uri, Airport.class);
}
}
我需要 UriBuilder
来构建绝对路径 (http://localhost/resources/airports/1),并且我知道我可以使用 UriInfo
类来完成此操作,但我无法将其注入(inject)适配器,因为它不是资源。当我在 URI 前面加上协议(protocol)、主机和资源路径时,解码确实有效。有什么方法可以让 UriBuilder 构建绝对路径而不需要我自己预先准备它?
更新
我想如果我自己创建一个 JAXB 上下文:
JAXBContext jc = JAXBContext.newInstance( "com.acme.foo:com.acme.bar" );
Unmarshaller u = jc.createUnmarshaller();
并自己在解码器上设置适配器,传递实体管理器以从数据库中获取正确的对象,而不是通过 URI 进行编码,这些也会被框架使用,还是会自己创建新实例,从而使这种方法静音?
最佳答案
如果您在 Marshaller
/Unmarshaller
上设置 XmlAdapter
实例,则该 XmlAdapter
实例将用于所有使用 @XmlJavaTypeAdapter
注释的位置以使用该类。
在 JAX-RS 环境(例如 Jersey)中,您可以使用 MessageBodyReader
/MessageBodyWriter
进行设置。
关于java - 使用 UriBuilder 从 XmlAdapter 创建绝对 URI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7688225/