天天看点

Spring集成web环境

1. ApplicationContext应用上下文获取方式

2. Spring提供获取应用上下文的工具

3. 案例测试

应用上下文对象是通过<code>new ClasspathXmlApplicationContext(spring配置文件)</code> 方式获取的,但是每次从容器中获得Bean时都要编写<code>new ClasspathXmlApplicationContext(spring配置文件)</code> ,这样的弊端是配置文件加载多次,应用上下文对象创建多次。

在Web项目中,可以使用<code>ServletContextListener</code>监听Web应用的启动,我们可以在Web应用启动时,就加载Spring的配置文件,创建应用上下文对象<code>ApplicationContext</code>,在将其存储到最大的域<code>servletContext域中,这样就可以在任意位置从域中获得应用上下文</code>ApplicationContext`对象了。

上面的分析不用手动实现,Spring提供了一个监听器<code>ContextLoaderListener</code>就是对上述功能的封装,该监听器内部加载Spring配置文件,创建应用上下文对象,并存储到<code>ServletContext</code>域中,提供了一个客户端工具<code>WebApplicationContextUtils</code>供使用者获得应用上下文对象。

所以我们需要做的只有两件事:

1、在<code>web.xml</code>中配置<code>ContextLoaderListener</code>监听器(导入spring-web坐标)

2、使用<code>WebApplicationContextUtils</code>获得应用上下文对象<code>ApplicationContext</code>

先准备好 UserDao、UserDaoImpl、UserService、UserServiceImpl

新建 Servlet 类 充当 web 层

UserDaoImpl

Spring集成web环境

UserServiceImpl

Spring集成web环境

导入Spring集成web的坐标 和 Servlet 依赖

配置<code>ContextLoaderListener</code>监听器,在 <code>web.xml</code> 配置下

Spring集成web环境

新建 Servlet 类 充当 web 层,通过工具获得应用上下文对象

运行:http://localhost:8080/userServlet

Spring集成web环境