ServletContextListener中使用spring容器的bean

本文介绍了Servlet生命周期,指出Servlet应由web server管理,而非Spring。还阐述了在servlet中使用spring容器管理业务对象的方法,即通过依赖查找获取对象引用。最后说明了springboot的加载方式,包括创建实现ServletContextListener接口的类,以及在启动类加@ServletComponentScan注解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、Servlet生命周期

Servlet的整个生命周期都是由Servlet容器来处理的。

如果把它硬放到Spring容器中去创建,Servlet对象是可被Spring容器建出来,但Servlet容器可能跟本就不知此Servlet存在,因此不在它的容器中。

所以,servlet只能交给web server来管理,不要交给spring管理。

web Server容器中,无论是Servlet,Filter,还是Listener都不是Spring容器管理的,因此在这些类中无法直接使用Spring注解的方式来注入Bean

二、Servlet context 加载 spring context,servlet使用spring context中的对象/bean

在使用spring容器的web应用中,业务对象间的依赖关系都可以用spring-context.xml文件来配置,并且由spring容器来负责依赖对象的创建。

如果要在servlet中使用spring容器管理业务对象,通常需要使用 WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()) 来获得WebApplicationContext,然后调用WebApplicationContext.getBean(“beanName”)来获得对象的引用,这实际上是使用了依赖查找来获得对象,并且在servlet代码中硬编码了应用对象的bean名字。

这种方式,相当于把spring容器中的bean加载到了servlet容器中,即把spring中的bean放到web.xml的bean中

三、springboot 加载方式

代码

创建一个类 实现 ServletContextListener接口
ServletContextListener 接口,它能够监听 ServletContext 对象的生命周期,实际上就是监听 Web 应用的生命周期。
当Servlet 容器启动或终止Web 应用时,会触发ServletContextEvent 事件,该事件由ServletContextListener 来处理。在 ServletContextListener 接口中定义了处理ServletContextEvent 事件的两个方法。


import com.example.demo.service;
import com.example.demo.config;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

@Slf4j
@WebListener
public class MyListener implements ServletContextListener {

    private BusinessService businessService;

    private SysConfig sysConfig;

    /**
     * 实现其中的初始化函数,当有事件发生时即触发
     * @param sce
     */
    public void contextInitialized(ServletContextEvent sce) {
            BusinessService businessService= WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()).getBean(BusinessService .class);
            this.businessService =businessService;
            SysConfig sysConfig= WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()).getBean(SysConfig.class);
            this.sysConfig=sysConfig;
    }
    /**
     * 实现其中的销毁函数
     * @param sce
     */
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("this is last destroyeed");
    }
}
启动类加上 @ServletComponentScan 注解
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值