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?
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.
In Spring Boot, you can use appContext. getBeanDefinitionNames() to get all the beans loaded by the Spring container.
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);
}
Been using the solution described here for a week, and it's working fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With