使用spring框架,应用启动时,加载数据
场景描述:
有时我们需要在应用启动时,加载某些不常变的数据到缓存中,避免每次请求时查询数据库或其它数据源,以提高性能(准备连接,建立连接,关闭连接,减少数据读取的IO数).如果应用中刚好用到spring框架,正好可以用spring的机制实现这个功能
解决方案:
1:写一个类,实现BeanPostProcessor接口,这个接口有两个方法。
(1):postProcessBeforeInitialization方法,在spring中定义的bean初始化前调用这个方法
(2):postProcessAfterInitialization方法,在spring中定义的bean初始化后调用这个方法
例子代码:
[java] public class CacheBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object obj, String arg1) throws BeansException {
try {
if(obj instanceof ColumnService) {
((ColumnService)obj).getColumnList();//加载栏目数据
}else if(obj instanceof TradeServiceImpl){
((TradeServiceImpl)obj).getTradeList();//加载行业数据
}
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
@Override
public Object postProcessBeforeInitialization(Object arg0, String arg1)
throws BeansException {
// TODO Auto-generated method stub
return arg0;
}
}
public class CacheBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object obj, String arg1) throws BeansException {
try {
if(obj instanceof ColumnService) {
((ColumnService)obj).getColumnList();//加载栏目数据
}else if(obj instanceof TradeServiceImpl){
((TradeServiceImpl)obj).getTradeList();//加载行业数据
}
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
@Override
public Object postProcessBeforeInitialization(Object arg0, String arg1)
throws BeansException {
// TODO Auto-generated method stub
return arg0;
}
}
2:在spring的xml文件中,添加
<!-- 初始缓存数据,初始化spring中定义的bean的前后都会用此实现类 -->
<bean id="cacheBeanPostProcessor" class="com.guagua.cache.CacheBeanPostProcessor"/>
3:在加载数据后,数据存在什么地方,由你来定,我这个例子是放到了一个“静态变量中”
[java] @Service("columnService")
public class ColumnServiceImpl implements ColumnService {
public static List<Column> columnList = new ArrayList<Column>();
@Autowired
private ColumnDao columnDao;
public void setColumnDao(ColumnDao columnDao) {
this.columnDao = columnDao;
}
@Override
public List<Column> getColumnList() throws Exception {
columnList = columnDao.getColumnList();
return columnList;
}
}
@Service("columnService")
public class ColumnServiceImpl implements ColumnService {
public static List<Column> columnList = new ArrayList<Column>();
@Autowired
private ColumnDao columnDao;
public void setColumnDao(ColumnDao columnDao) {
this.columnDao = columnDao;
}
@Override
public List<Column> getColumnList() throws Exception {
columnList = columnDao.getColumnList();
return columnList;
}
}
结束语:
如有疑问,请提出异议建意。
补充:软件开发 , Java ,