成都创新互联网站制作重庆分公司

详解springboot整合Listener的两种方式

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 ServletListenerRegistrationBeangetBean(){
 ServletListenerRegistrationBeanbean = new ServletListenerRegistrationBean<>(new SecondListener());
 return bean;
 }
}

总结

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


文章名称:详解springboot整合Listener的两种方式
新闻来源:http://cxhlcq.com/article/jddpde.html

其他资讯

在线咨询

微信咨询

电话咨询

028-86922220(工作日)

18980820575(7×24)

提交需求

返回顶部