我找不到参考指南,但通过一些代码探索和this mailing list thread from the archives 设法解决了配置问题。
由于某种原因,来自该邮件列表线程的建议不起作用(它忽略了来自 web.xml 的自定义 JSONProvider)。我可能还有其他问题。
最终,我放弃了web.xml 配置的想法,因为它已经用于提供javax.ws.rs.Application 并且(从查看@CXF 代码),CXF 似乎忽略了web.xml 中的init-param 元素如果它会找到一个应用程序。
此外,web.xml 配置中似乎没有表达 Map 类型的方法。这是基于线程和查看代码的猜想,所以我无法100%确认。
这就是我的 web.xml 的样子(这些更改前后相同):
<servlet>
<servlet-name>CXFServlet</servlet-name>
<display-name>CXF Servlet</display-name>
<servlet-class>org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>my.javax-ws-rs.Application</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
我需要在 my.javax-ws-rs.Application 类中进行更改。
只需在其中的单例列表中添加一个新的JSONProvider:
@Override
public Set< Object> getSingletons() {
final Set< Object> singletons = new HashSet<>();
// [SNIP -- existing singletons]
singletons.add( new my.provider.MyJSONProvider() );
return singletons;
}
my.provider.MyJSONProvider 的定义是其余魔法发生的地方(是的,这是我说我没有但最终不得不求助的“程序化”配置):
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON})
@Provider
public class MyJSONProvider<T> extends JSONProvider<T> {
public AdministrationUtilisatuerJSONProvider() {
{
Map<String, String> newNamespaceMap = new ConcurrentHashMap<>();
XmlSchema resource1SchemaAnnotation = Resource1.class.getPackage().getAnnotation(javax.xml.bind.annotation.XmlSchema.class);
String resource1Namespace = resource1SchemaAnnotation.namespace();
newNamespaceMap.put( resource1Namespace, "resource1JsonPrefix" );
XmlSchema resource2SchemaAnnotation = Resource2.class.getPackage().getAnnotation(javax.xml.bind.annotation.XmlSchema.class);
String resource2Namespace = resource2SchemaAnnotation.namespace();
newNamespaceMap.put( resource2Namespace, "resource2JsonPrefix" );
setNamespaceMap(newNamespaceMap);
}
// Or set this to "true" to ignore all that namespace stuff
// setIgnoreNamespaces(true);
// Don't write namespace for default xsi-type elements.
setWriteXsiType(false);
// [SNIP] -- Other JSONProvider configuration.
// Check source from CXF, but few comments in code.
}
关于让基于 Jettison 的 JSON 在 CXF 中工作的最后一点说明:您还需要在类路径中添加 cxf-rt-rs-extension-providers-X.Y.Z.jar。 CXF WHICH_JARS 文件中没有记录,但这是必需的。