在servlet或者filter或者Listener中使用spring的IOC容器的方法是:
WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
由于spring是注入的对象放在ServletContext中的,所以可以直接在ServletContext取出WebApplicationContext 对象:
WebApplicationContext webApplicationContext = (WebApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
事实上WebApplicationContextUtils.getWebApplicationContext方法就是使用上面的代码实现的,建议使用上面上面的静态方法
若是在ServletContextListener(注意不是其他各种Listener)中使用这个这个spring的IOC功能,则注意在web.xml配置文件中该listener应该配置在spring提供的ContextLoaderListener(这个listener是加载spring IOC配置文件)后面,否则会有问题。
本文介绍如何在Servlet、Filter或Listener中使用Spring的IOC容器,并提供了具体的代码示例。文章强调了在ServletContextListener中使用Spring IOC容器时web.xml配置的重要性。
555





