使用JerseyTest和Grizzly测试基于Spring的休息服务:依赖注入不起作用

时间:2014-02-10 18:15:00

标签: spring jersey

这是我的Rest WS:

@Path("/personService")    
@Service
public class PersonRestService {
    Logger logger = LoggerFactory.getLogger(PersonRestService.class);

    @Autowired
    private PersonService personService;

    @GET
@Path("{id}")
@Produces({ MediaType.APPLICATION_JSON })
public Person getPersonByID(@PathParam("id") String id) {
    logger.debug("getItemByID with id {}", id);
    return personService.getPersonById(id);
}

以下是单元测试:

   public class PersonServiceRestTest extends JerseyTest {

     public PersonServiceRestTest() throws Exception {
        super(new WebAppDescriptor.Builder("com.intesasanpaolo.web.rest.service").
                contextPath("test")
                .contextParam("contextConfigLocation", "classpath*:application-context/web-test-context.xml")
                .contextListenerClass(ContextLoaderListener.class)
                .build());
     }


@Test
public void testGetPerson() {
    Client client = Client.create();

    WebResource webResource = client.resource("http://localhost:9998/test/personService/1");

    ClientResponse response = webResource.type(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    System.out.println(response);

}

}

当我运行测试时,我收到personService.getPersonById(id)上的异常,因为personService未自动装配。 似乎由grizzly创建的所有其他服务都不共享上面定义的spring上下文:

INFO: Scanning for root resource and provider classes in the packages:
  com.intesasanpaolo.web.rest.service
10-feb-2014 19.10.01 com.sun.jersey.api.core.ScanningResourceConfig logClasses
INFO: Root resource classes found:
  class com.intesasanpaolo.web.rest.service.PersonRestService
  class com.intesasanpaolo.web.rest.service.MyResource

我阅读了很多讨论,但仍然没有解决方案。 任何的想法? 亲切的问候。 马西莫

1 个答案:

答案 0 :(得分:0)

好的,我发现了问题。 未共享上下文,因为WebAppDescriptor未配置SpringServlet。

工作配置如下。

super(new WebAppDescriptor.Builder("com.intesasanpaolo.web.rest.service")
                .contextPath("test")
                .contextParam("contextConfigLocation", "classpath*:application-context/web-test-context.xml")
                .servletClass(SpringServlet.class)
                .initParam("com.sun.jersey.api.json.POJOMappingFeature", "true")
                .contextListenerClass(ContextLoaderListener.class)
                .build());

希望这可以帮助某人;) 最大