java web程序启动自动运行方法(spring)

场景:将web项目部署到tomcat后,启动tomcat后自动运行程序重的某个方法。

环境:spring、springmvc

直接新建一个controller类,让该类实现ApplicationListener<ContextRefreshedEvent>,实现该接口的
public void onApplicationEvent(ContextRefreshedEvent arg0) 方法,
在该方法内部编写你要启动后执行的方法。

例如:我写的这个是启动后加载域名到缓存中:

import javax.annotation.Resource;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Controller;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

@Controller
public class DomainCacheController implements ApplicationListener<ContextRefreshedEvent>{

@Override
public void onApplicationEvent(ContextRefreshedEvent arg0) {
// TODO Auto-generated method stub

CacheManager cache = CacheManager.getInstance();

Cache domainCache = cache.getCache("domainCache");

Element element = null;

List<TopLevelDomain> allTop = topService.obtainAllTopLevelDomainByCompanyId(0);
for (TopLevelDomain top : allTop) {
element = new Element(top.getTopUrl(), top.getCompanyId());
domainCache.put(element);
}

List<SecondLevelDomain> allSecond = secondService.obtainAllSecondLevelDomainByCompanyId(0);
for (SecondLevelDomain second : allSecond) {
element = new Element(second.getSecondUrl(), second.getCompanyId());
domainCache.put(element);
}
}

}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值