废话不说,直接码上:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import com.yedong.listener.SecondListener;
/**
* 当使用注解@WebListener时,启动SpringBoot时会自动实例化ServletContextListener
* 但会优先加载使用@Bean 实例的化的 ServletListenerRegistrationBean工厂生产产生的ServletContextListener。
* 使用ServletListenRegistrationBean 和 使用注解实例化的互为补充,不排斥,都能实例化。
* @author YeDong
*/
@SpringBootApplication
@ServletComponentScan
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
@Bean
public ServletListenerRegistrationBean<SecondListener> getServletListenerRegistrationBean(){
ServletListenerRegistrationBean<SecondListener> bean = new ServletListenerRegistrationBean<SecondListener>(new SecondListener());
return bean;
}
}
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
/**
* 当使用注解@WebListener时,启动SpringBoot时会自动实例化ServletContextListener
* 但会优先加载使用@Bean 实例的化的 ServletListenerRegistrationBean工厂生产产生的ServletContextListener。
* @author YeDong
*
*/
@WebListener
public class FirstListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContextListener.super.contextInitialized(sce);
System.out.println("First>>>>>>Listener>>>>>>Init>>>>>>");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
ServletContextListener.super.contextDestroyed(sce);
}
}
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class SecondListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContextListener.super.contextInitialized(sce);
System.out.println("Second>>>>>>Listener>>>>>Init>>>>>>");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
ServletContextListener.super.contextDestroyed(sce);
}
}