|
2.3 Web Context设置 对于不依赖于应用服务器的Spring 上下文(Context)设置,通常在应用代码中通过FileSystemXmlApplicationContext或ClasspathXmlApplicationContext来获取。比如使用这样的代码来得到上下文: ApplicationContext ctx = new FileSystemXmlApplicationContext("config.xml");
1.ContextLoaderListener:一般的应用服务器如WAS都能先装载Listener,如果不是的话,那么只能使用ContextLoaderServlet。 2.ContextLoaderServlet:需要配置<load-on-startup>使得它率先装载。真正装载Context的类是ContextLoader,上面两个类只是两种调用ContextLoader的不同途径。ContextLoader内部实际调用的是XmlWebApplicationContext,其缺省配置文件为/WEB-INF/applicationContext.xml。 如果使用ContextLoaderListener,其在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>
WebApplicationContext一般由DispatcherServlet来初始化。在上下文层次结构上可以把它看成是ApplcationContext的子上下文。在缺省的情况下,DispatcherServlet装载的配置文件名称为其Servlet名称-Servlet.xml,但是可以通过contextConfigLocation参数来定制。DispatcherServlet在web.xml中的定义示例如下: <servlet><servlet-name>Dispatcher</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet </servlet-class><load-on-startup>2</load-on-startup></servlet><init-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/context/Webcontrollers.xml</param-value></init-param> |