详解springboot整合Listener的两种方式

发布时间:2020-10-14 23:06:05 作者:SUBEYZ
来源:脚本之家 阅读:175

1.通过注解

详解springboot整合Listener的两种方式

编写启动类

package cn.bl;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@SpringBootApplication
@ServletComponentScan
public class App {
 public static void main(String[] args) {
 SpringApplication.run(App.class, args);
 }
}

 编写一个监听器

package cn.bl.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class FirstListener implements ServletContextListener{
 @Override
 public void contextInitialized(ServletContextEvent sce) {
 System.out.println("init .. ");
 }
 @Override
 public void contextDestroyed(ServletContextEvent sce) {
 System.out.println("desroyed .. ");
 }
}

 当执行App的时候

详解springboot整合Listener的两种方式

2.通过函数

详解springboot整合Listener的两种方式

package cn.bl.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class SecondListener implements ServletContextListener{
 @Override
 public void contextInitialized(ServletContextEvent sce) {
 System.out.println("second servletListener init .. ");
 }
 @Override
 public void contextDestroyed(ServletContextEvent sce) {
 System.out.println("second servletListener destroy .. ");
 }
}

package cn.bl;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import cn.bl.listener.SecondListener;
@SpringBootApplication
public class App2 {
 public static void main(String[] args) {
 SpringApplication.run(App2.class, args);
 }
 @Bean
 public ServletListenerRegistrationBean<SecondListener>getBean(){
 ServletListenerRegistrationBean<SecondListener>bean = new ServletListenerRegistrationBean<>(new SecondListener());
 return bean;
 }
}

总结

以上所述是小编给大家介绍的springboot整合Listener的两种方式,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对亿速云网站的支持!

推荐阅读:
  1. SpringBoot 整合Redis 注解方式
  2. 如何玩转 SpringBoot 2 快速整合 Listener

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot 整合 listener

上一篇:用Python+OpenCV对比图像质量的几种方法

下一篇:Java虚拟机运行时数据区域汇总

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》