SpringBooot框架 ServlerConxtextListener的方法實現和註解實現的區別

廢話不說,直接碼上:

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);
    }
    
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章