准备工作:
开始之前先进行基础环境搭建
1.1 ApplicationContext应用 上下文获取方式
1.1.1 创建监听器
ContextLoaderListener.java
package com.tian.listener;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ContextLoaderListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent servletContextEvent) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//将Spring的应用上下文对象存储到ServletContext域中
servletContextEvent.getServletContext().setAttribute("context", context);
System.out.println("spring容器创建完毕....");
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
1.1.2 配置监听器
web.xml
UserServlet com.tian.web.UserServlet UserServlet /userServlet com.tian.listener.ContextLoaderListener
1.1.3 重新get请求 更换获取Spring上下文的方式
之前的方式:
现在的方式:从servletContext域中获取context
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
ServletContext servletContext = this.getServletContext();
ApplicationContext context = (ApplicationContext) servletContext.getAttribute("context");
UserServiceImpl bean = context.getBean(UserServiceImpl.class);
bean.save();
}
1.1.4 启动服务器测试
1.2 Spring提供获取应用上下文的工具
Spring提供了一个监听器ContextLoaderListener,该监听器内部加载Spring配置文件,创建应用上下文对象,并存储到ServletContext域中,提供了一个客户端工具WebApplicationContextUtils供使用者获得应用上下文对象。(可以把我们之前创建的监听器删了,现在用Spring提供的监听器)
1.2.1 导入Spring集成web的坐标
org.springframework spring-web 5.3.7
1.2.2 配置ContextLoaderListener监听器
web.xml
UserServlet com.tian.web.UserServlet UserServlet /userServlet contextConfigLocation classpath:applicationContext.xml org.springframework.web.context.ContextLoaderListener
1.2.3 开始测试
现在的UserServlet代码:
package com.tian.web;
import com.tian.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
// 获取ApplicationContext
ServletContext servletContext = this.getServletContext();
// 获取Spring Ioc容器的上下文
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
// 从Ioc容器获取bean
UserService userService = context.getBean(UserService.class);
// 调用bean的方法
userService.save();
}
}
启动服务器:



