编辑
是的ContextResolverFactory 为上下文解析器进行缓存...我以不同的方式工作,希望这会有所帮助 -
为日期创建 XMLAdapter 作为 spring bean
import java.util.Date;
import javax.inject.Inject;
import javax.inject.Named;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.apache.commons.lang3.time.DateFormatUtils;
@Named
public class RequestBasedXMLAdapter extends XmlAdapter<String, Date> {
@Inject
private RequestData requestData;
@Override
public String marshal(Date value) throws Exception {
return DateFormatUtils.format(value, requestData.getMyDateFormat());
}
@Override
public Date unmarshal(String value) throws Exception {
// i am not interested in incoming date
return new Date();
}
}
创建请求范围的 bean
import javax.inject.Named;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
@Named
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestData {
private String myDateFormat;
public String getMyDateFormat() {
return myDateFormat;
}
public void setMyDateFormat(String myQueryParam) {
this.myDateFormat = myQueryParam;
}
}
为 JAXBContext 创建上下文解析器
- 注入spring应用上下文
- 将您的 XMLAdapter 从上下文中定义为 spring bean
-
通过修改以下方法返回自定义 jaxbcontext(作为装饰器实现)
public JAXBMarshaller createMarshaller() throws JAXBException {
JAXBMarshaller marshaller = delegate.createMarshaller();
marshaller.setAdapter(adapter);
return marshaller;
}
public JAXBUnmarshaller createUnmarshaller() throws JAXBException {
JAXBUnmarshaller unmarshaller = delegate.createUnmarshaller();
unmarshaller.setAdapter(adapter);
return unmarshaller;
}
现在在您的 Resource 类中(您已在其中定义了 GET/POST 方法)
- 注入请求范围的bean RequestData
- 从 RequestData 中的查询/标头参数设置日期格式
将 Response 类中的 Date 字段注释为
@XmlJavaTypeAdapter(RequestBasedXMLAdapter.class)
private Date myCustomDate = new Date();
现在您应该可以根据您的要求更改日期格式了
另外请注意我使用的是 Moxy
老答案
我认为你可以通过返回不同的 ObjectMapper 来做到这一点......
试试
- 为 ObjectMapper 编写一个 ContextResolver
- 使用@Context 注入HTTPHeader
- 根据您的标头参数返回差异。使用适当日期格式的映射器
上述方法的缺点是相同的日期格式将应用于该响应中的所有日期。