web.xml中的Spring-test和ServletContextListener [英] Spring-test and ServletContextListener in web.xml

查看:101
本文介绍了web.xml中的Spring-test和ServletContextListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试通过我创建了RootTest.java

I created RootTest.java

@WebAppConfiguration
@ContextConfiguration("file:src/test/resources/root-context2.xml")
public class ReferenceServiceTest extends AbstractTestNGSpringContextTests {
...

spring上下文加载成功.但是我的全局变量没有实例化,因为web.xml被忽略了.在web.xml中,我有自己的侦听器类"(ServletContextListener的实现)和"context-param".如何使用Spring Integration Test上下文加载web.xml上下文(并调用所有应用程序启动侦听器)?

spring context loaded success. But my global variables not instantiated because web.xml ignored. In web.xml i have my own "listener-class"(implementation of ServletContextListener) and "context-param". How i can load web.xml context(and calls all application startup listeners) with spring integration test context?

推荐答案

如参考手册中所述,Spring MVC测试框架...

As stated in the reference manual, the Spring MVC Test Framework...

"通过TestContext加载实际的Spring配置 框架,并始终使用DispatcherServlet处理请求 因此,无需运行即可近似完整的集成测试 Servlet容器."

"loads the actual Spring configuration through the TestContext framework and always uses the DispatcherServlet to process requests thus approximating full integration tests without requiring a running Servlet container."

关键点是没有... Servlet容器".因此,web.xml不在此处显示.换句话说,web.xml中的配置无法影响使用Spring MVC测试框架的集成测试.

The key point there is "without ... a Servlet container". Thus web.xml does not come into the picture here. In other words, there is no way for configuration in web.xml to have an affect on integration tests using the Spring MVC Test Framework.

现在,话虽如此,可以这样向MockMvc注册Servlet Filter:

Now, having said that, it is possible to register a Servlet Filter with MockMvc like this:

mockMvcBuilder.addFilters(myServletFilter);

mockMvcBuilder.addFilters(myResourceFilter, "/resources/*");

您可以通过在MockMvc上执行断言之前将它们手动添加到ServletContext(实际上是Spring的MockServletContext)来配置context-param条目:

And you can configure context-param entries by adding them manually to the ServletContext (which is actually Spring's MockServletContext) before you execute assertions on MockMvc like this:

wac.getServletContext().setInitParameter(name, value);

但是...无法使用Spring MVC Test配置ServletContextListener.如果您希望对通过Spring MVC传递的所有请求应用 listener ,作为替代方案,您可以考虑实现自定义HandlerInterceptorWebRequestInterceptor(请参见

But... there is no way to configure a ServletContextListener using Spring MVC Test. If you want to have a listener applied to all of your requests that pass through Spring MVC, as an alternative you could consider implementing a custom HandlerInterceptor or WebRequestInterceptor (see Configuring interceptors in the reference manual).

此致

山姆

这篇关于web.xml中的Spring-test和ServletContextListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆