springboot - 整合Listener的两种方式

版权声明:本文为博主原创文章,欢迎转载,转载请注明本文链接! https://blog.csdn.net/qq_38238041/article/details/84727197

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的时候

2.通过函数

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 ServletListenerRegistrationBean<SecondListener>getBean(){
		ServletListenerRegistrationBean<SecondListener>bean = new ServletListenerRegistrationBean<>(new SecondListener());
		return bean;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_38238041/article/details/84727197