監聽器(Listener)的注冊方法和 Servlet 一樣,有兩種方式:代碼注冊或者注解注冊
1.代碼注冊方式
通過代碼方式注入過濾器
1
2
3
4
5
6
|
@Bean public ServletListenerRegistrationBean servletListenerRegistrationBean(){ ServletListenerRegistrationBean servletListenerRegistrationBean = new ServletListenerRegistrationBean(); servletListenerRegistrationBean.setListener( new IndexListener()); return servletListenerRegistrationBean; } |
IndexListener.Java類:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
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類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
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" ); } } |
把注解加到入口處啟動即可
1
2
3
4
5
6
7
|
@SpringBootApplication @ServletComponentScan public class SpringBootSimpleApplication { public static void main(String[] args) { SpringApplication.run(SpringBootSimpleApplication. class , args); } } |
以上所述是小編給大家介紹的Spring Boot的listener(監聽器)簡單使用實例詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://www.cnblogs.com/web424/p/6755963.html