002SpringIOC006Web环境下使用

1 创建工程

创建动态的Web工程。

2 导包

导入核心包:

1 spring-beans-4.0.0.RELEASE.jar
2 spring-context-4.0.0.RELEASE.jar
3 spring-core-4.0.0.RELEASE.jar
4 spring-expression-4.0.0.RELEASE.jar

导入依赖包:

1 commons-logging-1.1.3.jar

导入Web包:

1 spring-web-4.0.0.RELEASE.jar

3 配置文件

3.1 创建beans.xml配置文件

在src目录下创建Spring的配置文件。

3.2 在web.xml文件中加入监听器

在Web项目中使用Spring,需要配置监听器,在服务器启动的时候创建IOC容器,并放在application域中。

同时还要配置应用的上下文参数,指明配置文件的位置。

添加配置:

复制代码
 1 <!-- 应用上下文参数:可以通过ServletContext中getInitParameter("contextConfigLocation");方法获取。 -->
 2 <context-param>
 3     <param-name>contextConfigLocation</param-name>
 4     <param-value>classpath:beans*.xml</param-value>
 5 </context-param>
 6 
 7 <!-- 监听器:在服务器启动时,监听ServletContext对象创建和销毁,并创建和销毁IOC容器。 -->
 8 <listener>
 9     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
10 </listener>
复制代码

查看ContextLoaderListener的源码可以发现,该类实现了ServletContextListener接口,可以监听ServletContext对象的初始化和销毁。

通过配置contextConfigLocation参数可以指定在初始化ServletContext对象时加载的配置文件。

如果在Web环境下使用,那么创建的IOC容器的对象类型是XmlWebApplicationContext,如果不是在Web环境下使用,那么创建的IOC容器类型是ClassPathXmlApplicationContext。

4 获取容器

在Web环境下使用Spring容器,需要通过ServletContext获取:

1 ServletContext servletContext = request.getServletContext();
2 WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);

 

 
posted @   执笔未来  阅读(38)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· winform 绘制太阳,地球,月球 运作规律
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示