1.通过注解扫描完成Listener组件的注册
1.1 编写listener
/**
* Springboot 整合listener
*/
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class FirstListener implements ServletContextListener { @Override
public void contextInitialized(ServletContextEvent sce) {
// TODO Auto-generated method stub
System.out.println("listener Init");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
}
}
1.2编写启动类
/**
* springboot整合listener 方式一
* @author Administrator
*
*/
@SpringBootApplication
@ServletComponentScan
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
2.通过方法完成Listener组件的注册
2.1编写listener
public class SecondListener implements ServletContextListener { @Override
public void contextInitialized(ServletContextEvent sce) {
// TODO Auto-generated method stub
System.out.println("secondListener....");
} @Override
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub } }
2.2 编写启动器
/**
* SpringBoot 整合Listener方式2
*
* @author Administrator
*
*/
@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;
}
}