Spring入门笔记--Spring集成web环境
Spring集成web环境
idea社区版没有web功能,也不带tomcat插件,需要idea专业版。
IDEA配置
- 在项目的modules中增加web模块,并设置路径。
- 在Facets中也要新增web模块
- 在Artifacts中确保有classes和lib文件夹,我的没有lib,导致启动tomcat时老是报错找不到一些类,因为部署环境上没有。
- tomcat设置,添加external source和artifact
maven配置
如果使用tomcat10,javax已经替换成了jakarta,导包要正确,version和JDK版本有关。
com.guicedee.services
jakarta.servlet-api
1.1.1.7-jre8
老版本:
javax.servlet
javax.servlet-api
代码
在web项目中,可以使用ServletContextListener监听web应用的启动,web应用启动时,就夹在Spring的配置文件,创建上下文对象ApplicationContext,并存储在最大的域servletContext中。
监视器的实现:
public class ContextLoaderListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext servletContext = servletContextEvent.getServletContext();
String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
ApplicationContext app = new ClassPathXmlApplicationContext(contextConfigLocation);
servletContext.setAttribute("app", app); //存到域中
System.out.println("ContextLoaderListener.contextInitialized");
}
}
web.xml中:
contextConfigLocation
classpath:applicationContext.xml
实际上ContextLoaderListener和WebApplicationContextUtils类spring-web已经封装好了,可以直接使用,在获取上下文时:
com.yihao.listener.ContextLoaderListener
org.springframework.web.context.ContextLoaderListener
ServletContext servletContext = this.getServletContext();
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);
UserService userService = app.getBean(UserService.class);
但是如果使用了jakarta.servlet-api兼容有问题,自己写:
ServletContext servletContext = this.getServletContext();
ApplicationContext app = (ApplicationContext) servletContext.getAttribute("app");
UserService userService = app.getBean(UserService.class);