您好,登錄后才能下訂單哦!
1.通過注解
編寫啟動類
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的時候
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 ServletListenerRegistrationBean<SecondListener>getBean(){ ServletListenerRegistrationBean<SecondListener>bean = new ServletListenerRegistrationBean<>(new SecondListener()); return bean; } }
總結
以上所述是小編給大家介紹的springboot整合Listener的兩種方式,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對億速云網站的支持!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。