SpringBoot快速入门第二章,整合Listener (小白都能看得懂)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liushuai52013/article/details/87926724

主要内容

整合Listener

一、整合Listener

1.1 编写Listener

通过注解扫描完成Filter组件的注册
/**
 * springboot整合listener方式一
 *
 * 之前的配置方式
 * <listener>
 *     <listener-class>com.ls.springboot.listener.FirstListener</listener-class>
 * </listener>
 */
@WebListener
public class FirstListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("Listener ... init ....");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}


1.2 编写SpringBoot启动类

/**
 * springboot整合Listener方式一
 */

@SpringBootApplication
@ServletComponentScan
public class App {

    public static void main(String [] args){
        SpringApplication.run(App.class,args);
    }

}

二、通过完成Filter组件的祖册

2.1 编写Filter

/**
 * SpringBoot整合Listener方式二
 */
public class SecondListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("SecondLister...init...");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}

2.1 编写springboot启动类


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

}


SpringBoot入门项目地址下载: GitHub

猜你喜欢

转载自blog.csdn.net/liushuai52013/article/details/87926724