目录

spring boot启动完成和刷新事件

Java 2019-12-20 阅读 162 评论 0

web应用程序开发中的一个常见问题,是在应用程序启动完成后,初始化或调用一段代码。就像 JavaEE 的 ServletContextListener,当Servlet 容器启动(contextInitialized)或终止Web 应用(contextDestroyed)时,会触发ServletContextEvent 事件,该事件由ServletContextListener 来处理。Spring的ApplicationContextEvent 也提供了ContextClosedEvent, ContextRefreshedEvent, ContextStartedEvent, ContextStoppedEvent等一系列事件监听器。

下面介绍下 ContextRefreshedEvent 实现spring容器加载完毕和上下文刷新事件,事件可能会执行多次。

示例

实现ContextRefreshedEvent类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

@Component
public class ContextRefreshedListener implements ApplicationListener<ContextRefreshedEvent> {
	private static Logger logger = LoggerFactory.getLogger(ContextRefreshedListener.class);
	private SampleEvent sampleEvent;

	@Autowired
	public void setSampleEvent(SampleEvent sampleEvent) {
		this.sampleEvent = sampleEvent;
	}

	public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
		logger.info("Context Refreshed");
		sampleEvent.setEventFired(true);
	}
}

将输出:

2019-12-20 22:35:01.643  INFO 3995 --- [           main] t.c.s.f.FiringEventsApplication          : Starting FiringEventsApplication on bogon with PID 3995 (/Volumes/develop/workspace/java/my/spring-sample/firing_events/build/classes/java/main started by apple in /Volumes/develop/workspace/java/my/spring-sample/firing_events)
2019-12-20 22:35:01.646  INFO 3995 --- [           main] t.c.s.f.FiringEventsApplication          : No active profile set, falling back to default profiles: default
2019-12-20 22:35:02.312  INFO 3995 --- [           main] t.c.s.f.util.ContextRefreshedListener    : Context Refreshed
2019-12-20 22:35:02.317  INFO 3995 --- [           main] t.c.s.f.FiringEventsApplication          : Started FiringEventsApplication in 1.1 seconds (JVM running for 1.883)
2019-12-20 22:35:02.320  INFO 3995 --- [           main] t.c.s.f.FiringEventsApplication          : Is Event Fired : true

源码

源码地址:Github

最后更新 2019-12-20