通常,在web项目启动时,各位可能有疑问“Java中如何让web服务器启动的时候自动运行web程序中的某些业务”,如何在web项目启动时,做一些准备工作,如1.查询数据,放入缓存;2.清理原有数据缓存;等一系列操作。
在此我为大家下提供解决方案之一,直接上代码:
import javax.servlet.ServletContext;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ServletContextAware;
import com.xc.d.redis.RedisCacheUtil;
import com.xc.d.service.IConfigService;
@Service
public class StartupListener implements ApplicationContextAware, ServletContextAware, InitializingBean, ApplicationListener<ContextRefreshedEvent> {
private static Logger log = Logger.getLogger(StartupListener.class);
@Autowired
private IConfigService configService;// 此处可以注入Service / Dao
@Autowired
private RedisCacheUtil<String, String> redisTemplate;// redis缓存工具
@Override
public void setApplicationContext(ApplicationContext ctx) throws BeansException {
log.info("系统启动1 => StartupListener.setApplicationContext");
System.out.println("系统启动1 => StartupListener.setApplicationContext");
}
@Override
public void setServletContext(ServletContext context) {
log.info("系统启动2 => StartupListener.setServletContext");
System.out.println("系统启动2 => StartupListener.setServletContext");
}
@Override
public void afterPropertiesSet() throws Exception {
log.info("系统启动3 => StartupListener.afterPropertiesSet");
System.out.println("系统启动3 => StartupListener.afterPropertiesSet");
}
@Override
public void onApplicationEvent(ContextRefreshedEvent evt) {
if (evt.getApplicationContext().getParent() == null) {
return;
}
log.info(">>>>>>>>>>>>系统启动完成,onApplicationEvent()<<<<<<<<<<<<");
System.out.println(">>>>>>>>>>>>系统启动完成,onApplicationEvent()<<<<<<<<<<<<");
clearRedisDatas();// 清除redis缓存
getAllConfig();//加载网站配置
}
/** 清除所有缓存 */
public void clearRedisDatas() {
try {
redisTemplate.clear();
log.info("系统启动,清除所有缓存成功");
} catch (Exception e) {
log.error("系统启动,清除所有缓存失败", e);
}
}
/** 获取所有网站配置 */
public void getAllConfig() {
List<Config> configs = configService.getAllConfig();
//后续自行发挥,可存入缓存
}
}