Jersey在Spring中实现ContextResolver <JAXBContext>

rhi*_*don 7 spring json jaxb jersey

所以我正在写一个Spring(2.5(+ Jersey(1.1.4.1)并尝试使用ContextResolver创建一个JSONConfiguration.这是代码:

package com.rhigdon.jersey.config;

import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.api.json.JSONJAXBContext;

import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;

@Provider
public final class JAXBContextResolver implements ContextResolver<JAXBContext> {
  private JAXBContext context;

  public JAXBContextResolver() throws Exception {
    this.context = new JSONJAXBContext(JSONConfiguration.mappedJettison().build(), "com.rhigdon.core.model.");
  }

  public JAXBContext getContext(Class<?> aClass) {
    return context;
  }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是我的应用程序仍然返回默认映射:

{"id":"1","问题":"你的第一只宠物的名字是什么?"}

当我调试应用程序时,它实际上从未命中此代码.这是由于使用SpringServlet吗?这是我的web.xml中的Jersey Config:

<servlet>
    <servlet-name>Jersey Spring Web Application</servlet-name>
    <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>Jersey Spring Web Application</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>
Run Code Online (Sandbox Code Playgroud)

任何人都有类似的设置与JSONConfiguration工作?

rhi*_*don 12

您需要在春季环境中注册您的提供商:

<bean class="com.company.jersey.config.JAXBContextResolver"/>
Run Code Online (Sandbox Code Playgroud)

或者,如果您使用基于注释的配置,则需要使用@Component和包含类似的内容来注释您的提供程序类

<context:annotation-config />
<context:component-scan base-package="com.company.jersey" />
Run Code Online (Sandbox Code Playgroud)

到您的应用程序上下文配置

  • 这是一个非常明显的解决方案,但我想回答以防其他人有像我这样的空白.:) (2认同)