springboot - 整合Listener的两种方式

1.通过注解

springboot - 整合Listener的两种方式_第1张图片

编写启动类

package cn.bl;

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

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

 编写一个监听器

package cn.bl.listener;

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

@WebListener
public class FirstListener implements ServletContextListener{
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("init .. ");
	}
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("desroyed .. ");
	}
}

 当执行App的时候

springboot - 整合Listener的两种方式_第2张图片

2.通过函数

springboot - 整合Listener的两种方式_第3张图片

package cn.bl.listener;

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

public class SecondListener implements ServletContextListener{
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("second servletListener init .. ");
	}
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("second servletListener destroy .. ");
	}
}
package cn.bl;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;

import cn.bl.listener.SecondListener;

@SpringBootApplication
public class App2 {
	public static void main(String[] args) {
		SpringApplication.run(App2.class, args);
	}
	@Bean
	public ServletListenerRegistrationBeangetBean(){
		ServletListenerRegistrationBeanbean = new ServletListenerRegistrationBean<>(new SecondListener());
		return bean;
	}
}

 

 

你可能感兴趣的:(微服务)