您好,欢迎来到筏尚旅游网。
搜索
您的当前位置:首页SpringBooot框架 ServlerConxtextListener的方法实现和注解实现的区别

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

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- efsc.cn 版权所有 赣ICP备2024042792号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务