1.通過注解
成都創(chuàng)新互聯(lián)公司專注于格爾木企業(yè)網站建設,成都響應式網站建設公司,商城建設。格爾木網站建設公司,為格爾木等地區(qū)提供建站服務。全流程按需設計,專業(yè)設計,全程項目跟蹤,成都創(chuàng)新互聯(lián)公司專業(yè)和態(tài)度為您提供的服務
編寫啟動類
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); } }
編寫一個監(jiān)聽器
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 .. "); } }
當執(zhí)行App的時候
2.通過函數
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(){ ServletListenerRegistrationBean bean = new ServletListenerRegistrationBean<>(new SecondListener()); return bean; } }
總結
以上所述是小編給大家介紹的springboot整合Listener的兩種方式,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對創(chuàng)新互聯(lián)網站的支持!