Spring Boot的listener(監(jiān)聽器)簡單使用實例詳解
監(jiān)聽器(Listener)的注冊方法和 Servlet 一樣,有兩種方式:代碼注冊或者注解注冊
1.代碼注冊方式
通過代碼方式注入過濾器
@Bean
public ServletListenerRegistrationBean servletListenerRegistrationBean(){
ServletListenerRegistrationBean servletListenerRegistrationBean = new ServletListenerRegistrationBean();
servletListenerRegistrationBean.setListener(new IndexListener());
return servletListenerRegistrationBean;
}
IndexListener.Java類:
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類
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");
}
}
把注解加到入口處啟動即可
@SpringBootApplication
@ServletComponentScan
public class SpringBootSimpleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootSimpleApplication.class, args);
}
}
以上所述是小編給大家介紹的Spring Boot的listener(監(jiān)聽器)簡單使用實例詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
淺談SpringMVC的攔截器(Interceptor)和Servlet 的過濾器(Filter)的區(qū)別與聯(lián)系 及Spr
這篇文章主要介紹了淺談SpringMVC的攔截器(Interceptor)和Servlet 的過濾器(Filter)的區(qū)別與聯(lián)系 及SpringMVC 的配置文件,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
dubbo將異常轉(zhuǎn)換成RuntimeException的原因分析?ExceptionFilter
這篇文章主要介紹了dubbo將異常轉(zhuǎn)換成RuntimeException的原因分析?ExceptionFilter問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03
Java Jedis NOAUTH Authentication required問題解決方法
這篇文章主要介紹了Java Jedis NOAUTH Authentication required問題解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-07-07
SpringSessionRedis配置及發(fā)現(xiàn)的問題講解
今天小編就為大家分享一篇關(guān)于SpringSessionRedis配置及發(fā)現(xiàn)的問題講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-03-03
SpringBoot、mybatis返回樹結(jié)構(gòu)的數(shù)據(jù)實現(xiàn)
本文主要介紹了SpringBoot、mybatis返回樹結(jié)構(gòu)的數(shù)據(jù)實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
java實現(xiàn)excel和txt文件互轉(zhuǎn)

