有时候 需要在容器初始化完成后,加载些 代码字典或不常变的信息 放入缓存之类的,这里使用spring 初始化bean,并实例化
1.创建一个ApplicationListener类
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.context.ApplicationListener;import org.springframework.context.event.ContextRefreshedEvent;import org.springframework.stereotype.Component;@Component("aviatorRegisterConfigue")public class AviatorRegisterConfigue implements ApplicationListener<ContextRefreshedEvent> {// ContextRefreshedEvent为初始化完毕事件,spring还有很多事件可以利用 private static final Logger LOG = LoggerFactory.getLogger(AviatorRegisterConfigue.class); /** * 当一个ApplicationContext被初始化或刷新触发 */ @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (event.getApplicationContext().getDisplayName().equals("Root WebApplicationContext")) { //放入代码字典操作 LOG.info("redis缓存加载成功"); } }}
特别注意event.getApplicationContext().getDisplayName().equals(“Root WebApplicationContext”) 这里是防止 初始化完成 操作执行2次,原因是
在web 项目中(spring mvc),系统会存在两个容器,一个是root application context ,另一个就是我们自己的 projectName-servlet context(作为root application context的子容器)。
这种情况下,就会造成onApplicationEvent方法被执行两次。
但要相信真诚的爱情,对爱情永远怀有单纯的向往。