1.Spring如何在WEB应用中使用?
(1)需要加入额外jar包
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar
(2)Spring配置文件没什么不同
(3)如何创建IOC容器
①非WEB应用:在main方法中直接创建
②WEB应用:在WEB应用被服务器加载时创建IOC容器:
在ServletContextListener#contextInitialized(ServletContextEvent sce)方法中创建IOC容器。
③在WEB应用的其他组件中如何访问IOC容器?
在ServletContextListener#contextInitialized(ServletContextEvent sce)方法中创建IOC容器后,可以把其放在SeveltCOntext(即application域)的一个属性中。
④实际上,Spring配置文件的名字和位置应该也是可配的!将其配置当前WEB应用的初始化参数中较为合适。
(4)在WEB环境下使用Spring
①需要加入额外jar包
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar
②Spring配置文件没什么不同
③需要在web.xml文件中加入如下配置:
<!-- 配置Spring配置文件的名称和位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 启动IOC容器的ServletContextListener -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>