在servlet中获取spring的IOC容器

目录

1.起因

2.注意点

3.解决步骤

3.1导入spring依赖和spring-web依赖

3.2导入tomcat所需servlet的依赖

3.3在web.xml中配置以下语句

3.4在servlet类中的doGet或者doPost方法中使用以下语句获取容器:

3.5正常使用IOC容器


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);

3.5正常使用IOC容器

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值