指定定制应用上下文

我们正在使用泽西弹簧3将泽西1.x的一些数据服务从泽西1.x迁移到泽西2.x.

我们有几个inheritance自JerseyTest的测试类。 其中一些类使用未在web.xml文件中指定的自定义applicationContext.xml文件。

在Jersey 1.x中,扩展JerseyTest的测试类可以使用WebappDescriptor.Builder调用超级构造函数,可以传递上下文参数来设置或覆盖应用程序上下文路径。

例如

public MyTestClassThatExtendsJerseyTest() { super(new WebAppDescriptor.Builder("com.helloworld") .contextParam( "contextConfigLocation", "classpath:helloContext.xml") .servletClass(SpringServlet.class) .contextListenerClass(ContextLoaderListener.class) .requestListenerClass(RequestContextListener.class).build()); } 

如何用Jersey 2.x实现同样的目标?

我已经梳理了API文档 , 用户指南和一些来源,但无法找到答案。

谢谢。

让我们假设您的Application看起来像:

 @ApplicationPath("/") public class MyApplication extends ResourceConfig { /** * Register JAX-RS application components. */ public MyApplication () { // Register RequestContextFilter from Spring integration module. register(RequestContextFilter.class); // Register JAX-RS root resource. register(JerseySpringResource.class); } } 

您的JAX-RS根资源如:

 @Path("spring-hello") public class JerseySpringResource { @Autowired private GreetingService greetingService; @Inject private DateTimeService timeService; @GET @Produces(MediaType.TEXT_PLAIN) public String getHello() { return String.format("%s: %s", timeService.getDateTime(), greetingService.greet("World")); } } 

并且您可以直接从类路径获得名为helloContext.xml spring描述符。 现在,您想使用Jersey Test Framework测试getHello资源方法。 你可以写下你的测试:

 public class JerseySpringResourceTest extends JerseyTest { @Override protected Application configure() { // Enable logging. enable(TestProperties.LOG_TRAFFIC); enable(TestProperties.DUMP_ENTITY); // Create an instance of MyApplication ... return new MyApplication() // ... and pass "contextConfigLocation" property to Spring integration. .property("contextConfigLocation", "classpath:helloContext.xml"); } @Test public void testJerseyResource() { // Make a better test method than simply outputting the result. System.out.println(target("spring-hello").request().get(String.class)); } } 

这对我不起作用,因为我没有使用.xml样式配置,我正在使用@Configuration注释。 所以我不得不直接向ResourceConfig类提供应用程序上下文。

我在JerseyTest中定义了configure方法,如下所示:

 @Override protected Application configure() { ResourceConfig rc = new ResourceConfig(); AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class); rc.property("contextConfig", ctx); } 

其中SpringConfig.class是我的类,带有@Configuration注释并导入org.springframework.context.annotation.AnnotationConfigApplicationContext