欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot2.1.1自定义Listener的两种方式

程序员文章站 2022-05-01 12:27:15
...

环境

idea 2019
jdk1.8
maven3.6
spring boot2.1.1(目前springboot最高版本为2.1.8情况下,2.0以上测试过几个版本都可正常运行)
项目类型:jar

导入spring boot web启动器依赖

<dependency>
 		<groupId>org.springframework.boot</groupId>
  	    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

注意:spring boot自动配置的前提是>>所有组件都在核心启动类所在包及其子包下,所以本篇所有java类都是在核心类所在包及其子包下创建。

方式一(自动扫描)

创建一个类实现要监听的Listener接口,重写相关方法,在类上加@WebListener注解
package com.wn.demo.springboot.server;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class MyContextListener implements ServletContextListener {

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

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("ContextListener destory...");
    }
}
在配置类上添加@ServletComponentScan注解,这里方便起见就加在核心启动类上
package com.wn.demo.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@ServletComponentScan // 自动扫描自定义的Listener组件
@SpringBootApplication
public class SpringBootWeb2Application {

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

}

方式二(手动注册)

创建一个类实现要监听的Listener接口,重写相关方法
package com.wn.demo.springbootrestfulcrud.server;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("MyListener 启动");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("MyListener 销毁");
    }
}
在配置类中注册Listener
package com.wn.demo.springbootrestfulcrud.config;

import com.wn.demo.springbootrestfulcrud.server.MyFilter;
import com.wn.demo.springbootrestfulcrud.server.MyListener;
import com.wn.demo.springbootrestfulcrud.server.MyServlet;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

/**
 * server相关配置
 */
@Configuration
public class MyServerConfig {
    /**
     * 注册listener
     * @return Listener注册对象
     */
    @Bean
    public ServletListenerRegistrationBean<MyListener> myListener() {
    	// 创建Listener注册对象,将自定义的Listener作为构造参数传入
        return new ServletListenerRegistrationBean<>(new MyListener());
    }

}