一、启动Spring
对于使用Spring的Web应用,无须手动创建Spring容器,而是通过配置文件声明式的创建Spring容器。在Web应用中创建Spring容器有如下两种方式:
- 直接在web.xml文件中配置创建Spring容器
- 利用ServletContextListener实现
- 采用load-on-startup Servlet实现
- 利用第三方MVC框架的扩展点,创建容器
1.1 在web.xml中利用ServletContextListener监听器
这种方式最常见,为了让Spring容器随Web应用的启动而自动启动,借助于ServletContextListener监听器即可完成,该监听器可以在Web应用启动时回调自定义方法(该方法就可以启动Spring容器)。
Spring提供了一个ContextLoaderListener,该监听器类实现了ServletContextListener接口。该类可以作为Listener使用,它会在创建时自动查找WEB-INF/下的applicationContext.xml文件。因此,如果只有一个配置文件,并且文件名为applicationContext.xml,则只需在web.xml文件中增加如下配置片段即可:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
如果有多个配置文件需要载入,则需要使用<context-param.../>元素来确定配置文件的文件名。ContextLoaderListener加载时,会查找名为contextConfigLocation的初始化参数。因此,配置<context-param.../>时应制定参数名为contextConfigLocation。如下:
<!-- 指定多个配置文件 -->
<context-param>
<!-- 参数名为contextConfigLocation -->
<param-name>contextConfigLocation</param-name>
<!-- 多个配置文件之间以","隔开 -->
<param-value>WEB-INF/SpringConfig/*.xml,/WEB-INF/A.xml,/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</lis