Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Spring beans in JerseyTest

I'm trying to figure out how to access Spring beans from a subclass of JerseyTest. Extending JerseyTest I've managed to load the Spring context in my tests, but I haven't figured out how to access the spring context. My setup looks like this:

public abstract class SpringJerseyTest extends JerseyTest {
    public SpringJerseyTest() throws Exception {
        super(new WebAppDescriptor.Builder("com.acme.resources")
            .contextPath("/")
            .contextParam("contextConfigLocation", "classpath:applicationContext.xml")
            .servletClass(SpringServlet.class)
            .contextListenerClass(ContextLoaderListener.class)
            .build());
    }

}

The setup is using the default Grizzly Web Container. I've never used Grizzly before, but in Jetty I would do something like this:

    public Object getSpringBean(String beanName) {
        WebAppContext context = (WebAppContext) server.getHandler();
        ServletContext sc = context.getServletContext();
        WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(sc);
        return applicationContext.getBean(beanName);
    }

Could anyone point me in the right direction?

like image 610
ebaxt Avatar asked Jan 12 '11 06:01

ebaxt


People also ask

How do you get spring beans?

Ways to get loaded beans in Spring / Spring boot ApplicationContext. getBeanDefinitionNames() will return names of beans which is correctly loaded. getBean(String name) method using that we can get particular bean using bean name.

How do you get loaded beans in the spring?

In Spring Boot, you can use appContext. getBeanDefinitionNames() to get all the beans loaded by the Spring container.


2 Answers

I am using a naive approach but works

public ResourceIT()
    {
        super(new WebAppDescriptor.Builder("amazingpackage")
                .servletClass(SpringServlet.class)
                .contextParam("contextConfigLocation", "classpath:/spring/context.xml")
                .contextListenerClass(ContextLoaderListener.class)
                .contextPath("context")
                .build());
        injectedBean = ContextLoaderListener
                .getCurrentWebApplicationContext().getBean(InjectedBean.class);
    }
like image 62
Luis Ramirez-Monterosa Avatar answered Oct 12 '22 13:10

Luis Ramirez-Monterosa


Been using the solution described here for a week, and it's working fine.

like image 43
ebaxt Avatar answered Oct 12 '22 15:10

ebaxt