最近做项目,碰到这样的需求:在服务器启动的时候从数据库读取参数,将参数保存到内存缓存中
由于使用的是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 ;
}
}