Specify Custom Application Context Specify Custom Application Context spring spring

Specify Custom Application Context


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:

@Overrideprotected 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


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