Specify Custom Application Context

时光毁灭记忆、已成空白 提交于 2019-12-04 01:41:55

Lets assume your Application looks like:

@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);
    }
}

Your JAX-RS root resource like:

@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"));
    }
}

And you have spring descriptor named helloContext.xml available directly from your class-path. Now you want to test your getHello resource method using Jersey Test Framework. You can write your test like:

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));
    }
}

This didn't work for me as I was not using the .xml style configuration, I was using @Configuration annotations. So I had to directly provide the application context to the ResourceConfig class.

I defined the configure method in my JerseyTest like so:

@Override
protected Application configure() {
  ResourceConfig rc = new ResourceConfig();

  AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);
  rc.property("contextConfig", ctx);
}

where SpringConfig.class is my class with the @Configuration annotation and importing org.springframework.context.annotation.AnnotationConfigApplicationContext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!