Spring mvc启动监听-启动服务操作数据库

通常,在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();
		//后续自行发挥,可存入缓存		
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yqwang_cn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值