场景:将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);
}
}
}