在使用SpringMVC搭建demo时再使用WebApplicationContextUtils.getWebApplicationContext(ServletContext cn )方法获取WebApplicationContext对象时获取到的是空,可能的原因是因为在Web.xml中没有配置ContextLoaderListener监听或者没有配置ContextLoaderServlet的Servlet的类。
原理:服务器在启动时会读取Web.xml中的配置的监听,而ContextLoaderListener这个监听类的职责就是自动封装WebApplicationContext对象,由于没有配置该监听所有获取到对象是null。
解决方案:
在Web.xml中配置以下监听:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>