我正在尝试找出如何从 JerseyTest 的子类访问 Spring bean。 扩展 JerseyTest 我已经设法在我的测试中加载 Spring 上下文,但我还没有弄清楚如何访问 spring 上下文。我的设置如下所示:
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());
}
}
设置使用默认的 Grizzly Web 容器。我以前从未使用过 Grizzly,但在 Jetty 中我会做这样的事情:
public Object getSpringBean(String beanName) {
WebAppContext context = (WebAppContext) server.getHandler();
ServletContext sc = context.getServletContext();
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(sc);
return applicationContext.getBean(beanName);
}
谁能指出我正确的方向?
最佳答案
我使用的是一种天真的方法,但有效
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);
}
关于unit-testing - 在 JerseyTest 中访问 Spring bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4666105/