onApplicationEvent就是完成执行某个方法,我这里是从数据库查到省市编码code跟名字放到customCodeAndName里面使用。。。
import cn.txn.areamanage.AreaManageService;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import java.util.HashMap;
@Component
public class CustomCodeAndNameBeanPostProcessor implements ApplicationListener<ContextRefreshedEvent> {
private static HashMap<String, String> customCodeAndName = null;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
synchronized (CustomCodeAndNameBeanPostProcessor.class) {
if (event.getApplicationContext().getParent() != null) {
return;
}
if (customCodeAndName != null) {
return;
}
AreaManageService areaManageService = SpringContextUtil.getBean(AreaManageService.class);
HashMap<String, String> stringStringHashMap = areaManageService.selectAllCodeName();
this.customCodeAndName = stringStringHashMap;
}
}
public static HashMap<String, String> getCustomCodeAndName() {
return customCodeAndName;
}
}
因为使用springmvc有两个容器,这个方法会执行两次,要想只执行一次通过这个判断即可:
if (event.getApplicationContext().getParent() != null) {
return;
}