版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/java_cxrs/article/details/89818251
Listener?
监听器用于监听web应用中某些对象、信息的创建、销毁、增加,修改,删除等动作的发生,然后作出相应的响应处理。当范围对象的状态发生变化的时候,服务器自动调用监听器对象中的方法。常用于统计在线人数和在线用户,系统加载时进行信息初始化,统计网站的访问量等等。
如何在Spring Boot注册监听器?
步骤1:创建Listener实现ServletContextListener接口
package org.learn.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class TestListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("ServletContext对象创建");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
System.out.println("ServletContext对象销毁");
}
}
步骤2:项目启动类SpringBootLearnApplication增加注解@ServletComponentScan,利用该注解扫描注册监听器。
package org.learn;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@SpringBootApplication
@ServletComponentScan
public class SpringBootLearnApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootLearnApplication.class, args);
}
}
项目启动后我们从控制台输出可以看到红框的内容,表明我们的监听器注册成功!