目录
3.4在servlet类中的doGet或者doPost方法中使用以下语句获取容器:
1.起因
在某次作业中,非得使用spring配着servlet使用,本想直接进行注解注入,后面发现不对劲,在普通类可以直接获取spring的ioc容器,但在servlet中不可以,会报驱动错误
2.注意点
-
只适用于在servlet中获取ioc容器,mvc中的controller可以直接进行注解注入
-
只适用于tomcat10,10以下不能使用
3.解决步骤
3.1导入spring依赖和spring-web依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.3.20</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>6.0.10</version> </dependency>
3.2导入tomcat所需servlet的依赖
<dependency> <groupId>jakarta.servlet.jsp</groupId> <artifactId>jakarta.servlet.jsp-api</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>jakarta.servlet</groupId> <artifactId>jakarta.servlet-api</artifactId> <version>5.0.0</version> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>jakarta.servlet.jsp.jstl</artifactId> <version>2.0.0</version> </dependency>
3.3在web.xml中配置以下语句
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring配置文件所在相对地址</param-value> </context-param>
该类的作用是确保Spring的ApplicationContext
容器被正确初始化
3.4在servlet类中的doGet或者doPost方法中使用以下语句获取容器:
// 获取ServletContext ServletContext servletContext = getServletContext(); // 使用WebApplicationContextUtils从ServletContext中获取Spring的ApplicationContext ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);