1.web监听器的作用
web监听器可以监听ServletContext HttpSession ServletRequest 的创建删除属性变化
创建和销毁
ServletContextListener
HttpSessionListener
ServletRequestListener
属性变化
ServletContextAttributeListener
HttpSessionAttributeListener
ServletRequestAttributeListener
HttpSession对象绑定和解绑
HttpSessionBindingListener
ApplicationListener
2.实现接口监听器
package com.example.demo.common.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import lombok.extern.slf4j.Slf4j;
@WebListener
@Slf4j
public class DemoServletContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
log.debug("应用启动成功");
ServletContextListener.super.contextInitialized(sce);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
log.debug("应用停止成功");
ServletContextListener.super.contextDestroyed(sce);
}
}
3.app上添加注解@ServletComponentScan
@SpringBootApplication
@RestController
@Slf4j
@ServletComponentScan
public class DemoJavaApplication {
4.ApplicationListener
ContextRefreshedEvent
ApplicationContext 被初始化或刷新时,该事件被发布。这也可以在 ConfigurableApplicationContext接口中使用 refresh() 方法来发生。
此处的初始化是指:所有的Bean被成功装载,后处理Bean被检测并激活,所有Singleton Bean 被预实例化,ApplicationContext容器已就绪可用
ContextStartedEvent
当使用 ConfigurableApplicationContext (ApplicationContext子接口)接口中的 start() 方法启动 ApplicationContext 时,
该事件被发布。你可以调查你的数据库,或者你可以在接受到这个事件后重启任何停止的应用程序。
ContextStoppedEvent
当使用 ConfigurableApplicationContext 接口中的 stop() 停止 ApplicationContext 时,发布这个事件。你可以在接受到这个事件后做必要的清理的工作。
ContextClosedEvent
当使用 ConfigurableApplicationContext 接口中的 close() 方法关闭 ApplicationContext 时,该事件被发布。一个已关闭的上下文到达生命周期末端;它不能被刷新或重启。
RequestHandledEvent
这是一个 web-specific 事件,告诉所有 bean HTTP 请求已经被服务。只能应用于使用DispatcherServlet的Web应用。
在使用Spring作为前端的MVC控制器时,当Spring处理用户请求结束后,系统会自动触发该事件。
没法直接使用@Autowired来注入sevice进行数据库操作
5.ApplicationListener使用
package com.example.demo.common.listener;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;
@Component
@Slf4j
public class DemoApplicationListener implements ApplicationListener<ContextRefreshedEvent>{
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
//在web 项目中(spring mvc),系统会存在两个容器,一个是root application context(没有父类) ,另一个就是我们自己的 projectName-servlet context(作为root application context的子容器)。
//这种情况下,就会造成onApplicationEvent方法被执行两次。为了避免上面提到的问题,我们可以只在root application context初始化完成后调用逻辑代码
if(event.getApplicationContext().getParent()==null) {
//root application context(没有父类)
if(log.isDebugEnabled()) {
log.debug("ApplicationListenter Refreshed"+event.getApplicationContext().get);
}
}
}
}