import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
@Service
public class ParamsContextAdapter implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
System.out.println("test ApplicationListener");
}
}
- 确定ApplicationListener是对于哪种ApplicationEvent进行监听
-
同时集成了spring和springMVC的话,上下文中会存在父、子容器,(spring的<context-param>contextConfigLocation的父容器和springMVC的<init-param>contextConfigLocation的子容器), 在通过applicationContext发送通知的时候,事件可能会被两个容器同时发布。可以先排除是否由于配置有误造成。再
@Override public void onApplicationEvent(ContextRefreshedEvent event) { if(event.getApplicationContext().getParent() == null){ //需要执行的逻辑代码,当spring容器初始化完成后就会执行该方法。 } }
源码解析:
AbstractApplicationContext:
protected void finishRefresh() {
// Initialize lifecycle processor for this context.
initLifecycleProcessor();
// Propagate refresh to lifecycle processor first.
getLifecycleProcessor().onRefresh();
// Publish the final event. 将上下文ApplicationContext注入到ContextRefreshedEvent中
publishEvent(new ContextRefreshedEvent(this));
}
public void publishEvent(ApplicationEvent event) {
Assert.notNull(event, "Event must not be null");
if (logger.isTraceEnabled()) {
logger.trace("Publishing event in " + getDisplayName() + ": " + event);
}
getApplicationEventMulticaster().multicastEvent(event);
if (this.parent != null) {
this.parent.publishEvent(event); // 如果父容器不为空,父容器也publish事件源
}
}