整合 Listener
1,通过注解扫描完成 Listener 组件的注册
1 编写 Listener
/**
* springBoot整合Listener
*
*<listener>
* <listener-class>com.bjsxt.listener.FirstListener</listener-class>
*</listener>
*/
@WebListener
public class FirstListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("Listener...init......");
}
}
2 编写启动类
/**
* springBoot整合Listener方式一
*
*
*/
@SpringBootApplication
@ServletComponentScan
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
- 通过方法完成 Listener 组件注册
1 编写 Listener
/**
* springBoot整合Listener方式二。
*
*
*/
public class SecondListener implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated `在这里插入代码片`method stub
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("SecondListener..init.....");
}
}
2 编写启动类
/**
* SpringBoot整合Listener方式二
*
*
*/
@SpringBootApplication
public class App2 {
public static void main(String[] args) {
SpringApplication.run(App2.class, args);
}
/**
* 注册listener
*/
@Bean
public ServletListenerRegistrationBean<SecondListener> getServletListenerRegistrationBean(){
ServletListenerRegistrationBean<SecondListener> bean= new ServletListenerRegistrationBean<SecondListener>(new SecondListener());
return bean;
}
}