0
点赞
收藏
分享

微信扫一扫

第四篇:Spring Boot 整合listener


一、Spring Boot整合listener

第一种方案:通过注解扫描完成Listener的注册

  • 1.1 编写一个listener

@WebListener
public class FirstListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("FirstListener init .....");
}

@Override
public void contextDestroyed(ServletContextEvent sce) {

}
}

  • 1.2编写一个启动类,并在启动类上添加注解

/**
* SpringBoot整合Listener 方式 1
*/
@SpringBootApplication
@ServletComponentScan
public class SpringBootChapter1Application {

public static void main(String[] args) {
SpringApplication.run(SpringBootChapter1Application.class, args);
}
}

  • 1.3 启动项目及查看控制台
  • 第四篇:Spring Boot 整合listener_Spring Boot

第二种方案:通过方法完成Listener的注册

  • 2.1编写一个listener
  • 以前实现方式

<listener>
<listener-class>com.gblfy.listener.FirstListener</listener-class>
</listener>

  • Spring Boot实现方式:

 //SpringBoot整合Listener 方式 2
public class SecondListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("Secondlistener init .....");
}

@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}

  • 2.2 编一个启动类

/**
* SpringBoot整合Listener 方式 2
*/
@SpringBootApplication
public class SpringbootListenerApplication2 {

public static void main(String[] args) {
SpringApplication.run(SpringbootListenerApplication2.class, args);
}

@Bean
public ServletListenerRegistrationBean<SecondListener> getServletListenerRegistrationBean() {
ServletListenerRegistrationBean<SecondListener> bean = new ServletListenerRegistrationBean<SecondListener>(new SecondListener());
return bean;
}
}

  • 2.3 启动项目及查看控制台

第四篇:Spring Boot 整合listener_Spring Boot_02

本文源码下载:

github地址:
​​​https://github.com/gb-heima/Spring-Boot-Actual-Combat/tree/master/parent/spring-boot-chapter-4​​


举报

相关推荐

0 条评论