ApplicationContext在运行期会自动检测到所有实现了ApplicationListener的bean对象,并将其作为事件接收对象。当ApplicationContext的publishEvent方法被触发时,每个实现了ApplicationListener接口的bean都会收到ApplicationEvent对象,每个ApplicationListener可根据事件类型只接收处理自己感兴趣的事件,比如上面的StudentAddListener只接收StudentAddEvent事件。
http://blog.csdn.net/liuwenbo0920/article/details/7263766(非常好)
http://yangyongbyjava.iteye.com/blog/1600581
http://www.th7.cn/Program/java/201408/271385.shtml(ApplicationListener接口中的onApplicationEvent被调用两次解决方案)
Spring监听 ApplicationListener
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
importorg.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Component
public class InitDataListener implements
ApplicationListener { //ContextRefreshedEvent为初始化完毕事件
private static final Logger LOGGER =Logger
.getLogger(InitDataListener.class);
// 缓存管理器
@Autowired
@Qualifier("dictCacheManager")
private DictCacheManager dictCacheManager;
@Override
public voidonApplicationEvent(ContextRefreshedEvent event) {
final ApplicationContext app= event.getApplicationContext();
if (null ==app.getParent()
&&"Root WebApplicationContext".equals(app.getDisplayName())) { //当存在父子容器时,此判断很有用
//读取字典配置
Map config =new HashMap();
try {
config= PathUtil.getProperties("dataDictConfig.properties");
finalString mKey = config.get("dataDictKey");
if(StringUtils.isNotBlank(mKey)) {
DictCacheManager.M_KEY= mKey;
}
} catch(Exception e) {
LOGGER.error("Load\"dataDictConfig.properties\" failure!", e);
}
//判断是否立即加载数据字典到Redis
if("false".equals(config.get("lazyLoad"))) { //立即加载数据字典数据到Redis缓存服务器
dictCacheManager.init();
}
}
}
}
}