有时候我们可能需要在Spring Boot 容器启动时做一些操作,执行一些代码Spring 提供的监听器可以很方便的实现这些需求
容器监听类
容器启动时监听
import org
.springframework
.context
.ApplicationListener
;
import org
.springframework
.context
.annotation
.ComponentScan
;
import org
.springframework
.context
.event
.ContextRefreshedEvent
;
@ComponentScan
public class ApplicationStartingListener implements ApplicationListener<ContextRefreshedEvent>{
@Override
public void onApplicationEvent(ContextRefreshedEvent event
) {
}
}
容器启动完成时监听
import com
.alibaba
.excel
.event
.Order
;
import org
.springframework
.context
.ApplicationListener
;
import org
.springframework
.context
.annotation
.ComponentScan
;
import org
.springframework
.context
.event
.ContextRefreshedEvent
;
@ComponentScan
public class ApplicationStartingListener implements ApplicationListener<ContextRefreshedEvent>, Order
{
@Override
public void onApplicationEvent(ContextRefreshedEvent event
) {
}
@Override
public int order() {
return 0;
}
}
启动类配置
在启动类中进行加载
import com
.xma
.blog
.runner
.ApplicationStartingListener
;
import org
.springframework
.boot
.SpringApplication
;
import org
.springframework
.boot
.autoconfigure
.SpringBootApplication
;
@SpringBootApplication
public class Java8Application {
public static void main(String
[] args
) {
SpringApplication application
= new SpringApplication(Java8Application
.class);
application
.addListeners(new ApplicationStartingListener());
application
.run(args
);
}
}
web生命周期监听(Tomcat生命周期监听)
监听器配置
import javax
.servlet
.ServletContextEvent
;
import javax
.servlet
.ServletContextListener
;
import javax
.servlet
.annotation
.WebListener
;
@WebListener
public class ApplicationStartingRunner implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce
) {
}
@Override
public void contextDestroyed(ServletContextEvent sce
) {
}
}
启动类配置
import org
.springframework
.boot
.SpringApplication
;
import org
.springframework
.boot
.autoconfigure
.SpringBootApplication
;
import org
.springframework
.boot
.web
.servlet
.ServletComponentScan
;
import org
.springframework
.context
.annotation
.ComponentScan
;
@SpringBootApplication
@ServletComponentScan
public class Java8Application {
public static void main(String
[] args
) {
SpringApplication
.run(Java8Application
.class, args
);
}
}