业务需求中,可能会有一些逻辑需要在应用启动完成后,例如字典缓存,资源池初始化等等,代码如下
public class InitApplication implements ApplicationContextAware,ApplicationListener<ContextRefreshedEvent> { private Logger logger = LoggerFactory.getLogger(InitApplication.class); private ApplicationContext application; @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { if (!ContextRefreshedEvent.class.getName().equals(contextRefreshedEvent.getClass() .getName())) { return; }
//在web 项目中(spring mvc),系统会存在两个容器,
//一个是root application context ,另一个就是 projectName-servlet context(作为root application context的子容器),所以此方法会加载多次
//以下判断就可以防止多次加载 if (!("Root WebApplicationContext").equalsignorance(event.getApplicationContext().getDisplayName())){
return;
}
//业务逻辑,自行添加
} //此方法用于获取spring上下文,可以方便的拿取各种bean @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.application = applicationContext; } }