文章目录
一、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");
}
}