web应用中自动加载ApplicationContext

来自《 spring2.0 宝典》第三章
 
加载器目前有两种选择: ContextLoaderListener ContextLoaderServlet
这二者在功能上彻底等同,只是一个是基于 Servlet2.3 版本中新引入的 Listener 接口实现,而另外一个基于 Servlet 接口实现。开发中可根据目标 Web 容器的实际状况进行选择。 中,

配置很是简单,在 web.xml 中增长:
< listener >
  < listener-class >
       org.springframework.web.context.ContextLoaderListener
  </ listener-class >
</ listener >

或:
< servlet >
    < servlet-name > context </ servlet-name >
    < servlet-class >
       org.springframework.web.context.ContextLoaderServlet
    </ servlet-class >
    < load-on-startup > 1 </ load-on-startup >
</ servlet >

经过以上配置, Web 容器会自动加载 /WEB-INF/applicationContext.xml 初始化
ApplicationContext
实例,若是须要指定配置文件位置,可经过 context-param 加以指定:
< context-param >
    < param-name > contextConfigLocation </ param-name >
    < param-value > /WEB-INF/myApplicationContext.xml </ param-value >
</ context-param >

配置完成以后,便可经过
WebApplicationContextUtils.getWebApplicationContext
方法在 Web 应用中获取 ApplicationContext 引用。
如:
       ApplicationContext ctx=WebApplicationContextUtils.getWebApplicationContext();
            LoginAction action=(LoginAction)ctx.getBean( "action" );
相关文章
相关标签/搜索