以前编写配置 Listener
<listener> <listener-class>com.neuedu.listener.FirstListener</listener-class> </listener>
SpringBoot 整合Listener方式一
通过注解扫描完成Listener组件的注册
- 编写Listener
package com.neuedu.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; /** * SpringBoot 整合 Listener 方式一 * 我们这里创建了一个Servlet上下文的监听器,实现ServletContextListener接口即可 * @author 清水三千尺 * */ @WebListener public class FirstListener implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent sce) { // TODO Auto-generated method stub } @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("FirstListener...init...."); } }
- 编写启动类
package com.neuedu; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; /** * SpringBoot 启动类 * @author 清水三千尺 * */ @SpringBootApplication @ServletComponentScan //在SpringBoot启动时会扫描@WebListener,并将该类实例化 public class App { public static void main(String[] args) throws Exception { SpringApplication.run(App.class, args); } }
- 启动测试
控制台结果:
SpringBoot 整合Listener方式二
通过方法完成Listener组件的注册
- 编写Listener
package com.neuedu.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * SpringBoot 整合 Listener 方式二 * @author 清水三千尺 * */ public class SecondListener implements ServletContextListener { @Override public void contextDestroyed(ServletContextEvent sce) { // TODO Auto-generated method stub } @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("SecondListener...init...."); } }
- 编写启动类
package com.neuedu; 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 com.neuedu.listener.SecondListener; /** * SpringBoot 启动类 * @author 清水三千尺 * */ @SpringBootApplication public class App2 { public static void main(String[] args) throws Exception { SpringApplication.run(App2.class, args); } /** * 注册Listener */ @Bean public ServletListenerRegistrationBean<SecondListener> getListenerRegistrationBean() { //完成SecondListener的注册 ServletListenerRegistrationBean<SecondListener> bean = new ServletListenerRegistrationBean<SecondListener>(new SecondListener()); return bean; } }
- 启动测试
控制台结果:
作者:辽A丶孙悟空
链接:https://www.jianshu.com/p/a8ac23c6baa4
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。