你可以创建一个MessageBodyWriter
对于这个用例。通过ContextResolver
机制你可以获得JAXBContext
与您的域模型相关联。然后你可以获得一个Marshaller
来自JAXBContext
并设置JAXB_SCHEMA_LOCATION
就可以了,做元帅。
package org.example;
import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import javax.ws.rs.ext.*;
import javax.xml.bind.*;
@Provider
@Produces(MediaType.APPLICATION_XML)
public class FormattingWriter implements MessageBodyWriter<Object>{
@Context
protected Providers providers;
public boolean isWriteable(Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return true;
}
public void writeTo(Object object, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, Object> httpHeaders,
OutputStream entityStream) throws IOException,
WebApplicationException {
try {
ContextResolver<JAXBContext> resolver
= providers.getContextResolver(JAXBContext.class, mediaType);
JAXBContext jaxbContext;
if(null == resolver || null == (jaxbContext = resolver.getContext(type))) {
jaxbContext = JAXBContext.newInstance(type);
}
Marshaller m = jaxbContext.createMarshaller();
m.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "foo bar");
m.marshal(object, entityStream);
} catch(JAXBException jaxbException) {
throw new WebApplicationException(jaxbException);
}
}
public long getSize(Object t, Class<?> type, Type genericType,
Annotation[] annotations, MediaType mediaType) {
return -1;
}
}
UPDATE
还有一个问题。我的休息资源和提供者之间有什么联系?
您仍然以相同的方式实施您的资源。这MessageBodyWriter
机制只是一种覆盖 XML 写入方式的方法。这@Provider
注释是 JAX-RS 应用程序自动注册此类的信号。
我的资源类将返回Foo
目的。我认为我应该实施MessageBodyWriter<Foo>
?
你可以将其实现为MessageBodyWriter<Foo>
如果您只想将其应用于Foo
班级。如果您希望它不仅仅适用于Foo
你可以实施isWriteable
方法为适当的类返回 true。