SpringBoot整合Lintener

1.通过扫描完成Lintener组件的注册

1.1编写Listener

/**
 * springboot整合Lintener 方式一
 * 在web.xml中如何配置Listener
 * <listener>
 *     <listener-class>com.demo.istener.FirstListener</listener-class>//实例化listener全名
 * </listener>
 *
 * servlet上下文的监听器
 */
@WebListener
public class FirstListener implements ServletContextListener {
    /**
     * 当servlet容器终止web
     *
     * @param sce
     */
    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }

    /**
     * 当servletr容器启动web
     * @param sce
     */
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("Listener....init...");
    }
}

1.2编写启动类

 

/**
 * springboot整合Lintener 方式一
 */
@SpringBootApplication
@ServletComponentScan
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class,args);
    }
}

 

1.3启动main方法

 

2.通过方法完成Lintener组件的注册

2.1 编写Listener

/**
 * springboot整合Lintener 方式二
 */
public class SecondListener implements ServletContextListener {

    /**
     * servletr容器启动web
     * @param sce
     */
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("SecondListener....init...");
    }

    /**
     * servlet容器终止web
     * @param sce
     */
    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}

2.2编写启动类

/**
 * springboot整合Lintener 方式二
 */
@SpringBootApplication
public class App2 {
    public static void main(String[] args) {
        SpringApplication.run(App2.class,args);
    }

    /**
     * 注册Listener
     * @return
     */
    @Bean
    public ServletListenerRegistrationBean<SecondListener> getServletListenerRegistrationBean(){
        ServletListenerRegistrationBean<SecondListener> bean=new ServletListenerRegistrationBean<>(new SecondListener());
        return bean;
    }
}

 2.3启动,结果

 

 

小结 整合Listener两种方式:1.@WebListener  @SpringBootApplication @ServletContenerScan   2.@SpringBootApplication @Bean ServletListenerRegistrationBean<SecondListener>

posted @ 2019-05-11 17:50  又又IT  阅读(160)  评论(0编辑  收藏  举报