spring 启动完成后事件监听器处理

有时候我们在spring容器启动完成后,我们需要做一些处理动作,这个时候怎么做呢?

spring提供了事件监听器的处理机制。

spring提供了内置的几类的事件:

ContextClosedEvent   、ContextRefreshedEvent  、ContextStartedEvent  、ContextStoppedEvent   、RequestHandleEvent

在spring容器启动完成后会触发ContextRefreshedEvent事件。

我们可以创建一个ContextRefreshedEvent事件监听器。

public class DataSourceInitListener  implements ApplicationListener<ContextRefreshedEvent> {
	
	protected static final Logger LOGGER = LoggerFactory.getLogger(DataSourceInitListener.class);
	
	@SuppressWarnings("unchecked")
	@Override
	public void onApplicationEvent(ContextRefreshedEvent ev) {
		//防止重复执行。
		if(ev.getApplicationContext().getParent() == null){
		
			
		}
	}

}

  这个时候我们可以在这里写相关代码。

原文地址:https://www.cnblogs.com/yg_zhang/p/3662445.html