Spring Boot的listener(监听器)简单使用实例详解

Spring Boot的listener(监听器)简单使用实例详解

监听器(Listener)的注册方法和 Servlet 一样,有两种方式:代码注册或者注解注册

1.代码注册方式

通过代码方式注入过滤器

代码语言:javascript代码运行次数:0运行复制@Bean

public ServletListenerRegistrationBean servletListenerRegistrationBean(){

ServletListenerRegistrationBean servletListenerRegistrationBean = new ServletListenerRegistrationBean();

servletListenerRegistrationBean.setListener(new IndexListener());

return servletListenerRegistrationBean;

}IndexListener.Java类:

代码语言:javascript代码运行次数:0运行复制package com.example.Listener;

import javax.servlet.ServletContextEvent;

import javax.servlet.ServletContextListener;

public class IndexListener implements ServletContextListener{

@Override

public void contextDestroyed(ServletContextEvent arg0) {

System.out.println("IndexListener contextDestroyed method");

}

@Override

public void contextInitialized(ServletContextEvent arg0) {

System.out.println("IndexListener contextInitialized method");

}

}2.注解方式

通过注解方式注入过滤器

IndexListener2.Java类

代码语言:javascript代码运行次数:0运行复制package com.example.Listener;

import javax.servlet.ServletContextEvent;

import javax.servlet.ServletContextListener;

import javax.servlet.annotation.WebListener;

@WebListener

public class IndexListener2 implements

ServletContextListener{

@Override

public void contextDestroyed(ServletContextEvent arg0) {

System.out.println("IndexListener2 contextDestroyed method");

}

@Override

public void contextInitialized(ServletContextEvent arg0) {

System.out.println("IndexListener2 contextInitialized method");

}

}把注解加到入口处启动即可

代码语言:javascript代码运行次数:0运行复制@SpringBootApplication

@ServletComponentScan

public class SpringBootSimpleApplication {

public static void main(String[] args) {

SpringApplication.run(SpringBootSimpleApplication.class, args);

}

}以上所述是Spring Boot的listener(监听器)简单使用实例详解,希望对大家有所帮助

相关推荐

耳机插电脑只有一边有声音怎么办 耳机一个没声音了解决方法【详解】
黑神话黄袍员外在哪里-悟空黄袍员外具体位置介绍
365登录次数限制

黑神话黄袍员外在哪里-悟空黄袍员外具体位置介绍

📅 09-12 👁️ 5632
Global Family English 地球家族英语[复制链接]
365现在还能安全提款吗

Global Family English 地球家族英语[复制链接]

📅 08-31 👁️ 3139
蒙古语的爸爸叫什么称呼
365登录次数限制

蒙古语的爸爸叫什么称呼

📅 08-04 👁️ 7149
怎么用txt打开文件?win10使用记事本打开文件的方法
365登录次数限制

怎么用txt打开文件?win10使用记事本打开文件的方法

📅 09-16 👁️ 8678
融360匹配到天源花,天源花签约借款显示资金匹配中多久可以到账?
iPhone 批量删除短信的两种方法
365bet直播

iPhone 批量删除短信的两种方法

📅 07-20 👁️ 5669
博瑞1.8t和2.4l哪个好
365现在还能安全提款吗

博瑞1.8t和2.4l哪个好

📅 07-05 👁️ 4676
游戏手机会是下一个美图手机吗?
365现在还能安全提款吗

游戏手机会是下一个美图手机吗?

📅 08-21 👁️ 2888