Search code examples
javaspringtestingjerseyjersey-2.0

How to access Spring Bean from JerseyTest subclass


Here is my abstract class which starts Jersey with given Spring context:

public abstract class AbstractJerseyTest extends JerseyTest {

public void setUp() throws Exception {
    super.setUp();
}

@AfterClass
public void destroy() throws Exception {
    tearDown();
}

@Override
protected URI getBaseUri() {
    return URI.create("http://localhost:9993");
}

@Override
protected Application configure() {
    RestApplication application = new RestApplication();

    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);
    properties.put("contextConfigLocation", "classpath:spring-context-test.xml");

    application.setProperties(properties);
    application.register(this);
    return application;
}
}

So, the problem is that I need to access Spring bean from my test to populate database with some data.

Jersey version is 2.6

Also I found a similar question here

But it's related to Jersey 1.x so it doesn't work for Jersey 2.x

Could anyone point me in the right direction?


Solution

  • Solution was really simple. I added:

    @Autowired
    private Repository repository;
    

    to the AbstractJerseyTest and this field was automatically autowired during test startup. I don't know details about how it works, but it seems that when I register instance of the test in REST application

    application.register(this);
    

    it automatically autowires all beans in the test.