1. 程式人生 > >啟動伺服器時將配置引數從資料庫中載入到快取

啟動伺服器時將配置引數從資料庫中載入到快取

最近做專案,碰到這樣的需求:在伺服器啟動的時候從資料庫讀取引數,將引數儲存到記憶體快取中
由於使用的是spring的自動注入方式,一開始用@component註解在啟動的時候載入查詢配置引數的bean,由於bean中要用到其他bean來查詢,但此時都為null
查詢相關資料,發現@PostConstruct可以解決

/**
 * 引數配置相關服務類
 * @author Dell
 *
 */
@Service("configService")
public class ConfigService extends BasicService{

	private CacheManagerImpl cacheManagerImpl = new CacheManagerImpl();;

	/**
	 * 載入配置引數到系統快取
	 * @PostConstruct 當前bean初始化完成之後,自動執行帶有@PostConstruct註解的方法 
	 */
	@PostConstruct
	public void loadConfig(){
		List<Config> configs = findAllConfig(0, -1);
		for (Config config : configs) {
			if (null != config.get_parentId() && config.get_parentId() != 0) {
				cacheManagerImpl.putCache(config.getOptionName(), config.getOptionVal(), 0);
			}
		}
	}
	
	/**
	 * 查詢所有
	 * @param offset
	 * @param pagesize
	 * @return
	 */
	public List<Config> findAllConfig(int offset , int pagesize){
		List<Config> mBeanList = new ArrayList<Config>();
		String hql = "from Config" ;
		List<Object> list = dao.findPage(hql, offset, pagesize);
		if(null != list && list.size() > 0){
			for(Object obj : list){
				Config config = (Config)obj;
				config.set_parentId(config.getParentID());
				mBeanList.add(config);
			}
		}
		return mBeanList ;
	}
}