1. 程式人生 > >java web程式啟動自動執行方法(spring)

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);
}
}

}