我们经常会在项目中碰到需要加载一些常量到内存中,以便不比每次需要使用时都去查询数据库, 如,一些国家信息,省份信息,地址信息等 不会变动 或变动很少,但数据量又比较大的数据, 这时我们就需要把这些数据加载进内存,需要使用时直接从内从中取。 下面是代码:
Dao 以下 我就不发了。
首先定义一个类,在这个类中进行调用DAO查询数据库 ,加载出数据
- public class StartOnLoadService {
- public static Map<String,List> dictionaryInfoMap = new HashMap<String, List>(); //保存国籍信息
- private CountryService countryService; //受Spring 管理的Service 方法 调用Dao取数据
- /**
- * Spring 容器初始化时加载
- */
- public void loadData() {
- List optionList = countryService.getAllCountry();
- dictionaryInfoMap.put("nationalMap", optionList);
- }
- public CountryService getCountryService() {
- return countryService;
- }
- public void setCountryService(CountryService countryService) {
- this.countryService = countryService;
- }
- }
然后定义一个类 实现接口 BeanPostProcessor
- public class PBSTrackManagerPostProcessor implements BeanPostProcessor {
- public Object postProcessAfterInitialization(Object obj, String arg1)
- throws BeansException {
- if(obj instanceof StartOnLoadService) {
- ((StartOnLoadService)obj).loadData(); //调用方法加载数据
- }
- return obj;
- }
- public Object postProcessBeforeInitialization(Object arg0, String arg1)
- throws BeansException {
- return arg0;
- }
- }
Spring 配置
- <!-- 自动加载国家信息到 内存 -->
- <bean id="pbsTrackManagerPostProcess" class="com.mangocity.vacationhotel.business.action.PBSTrackManagerPostProcessor"/>
- <!--如果用注解的方式,在需要加载的类上加上@Service即可,这样spring才会读取注解配置加载文件2014-11-14 by zhang-->
- <bean id="startOnLoadService" class="com.mangocity.vacationhotel.business.service.impl.StartOnLoadService">
- <property name="countryService" ref="countryService"/>
- </bean>
就这样在Spring 启动时 数据就会被加载到 上面 StartOnLoadService 中的 dictionaryInfoMap 中。
/分割线/
下面把国籍信息显示在页面上:
- public class OptionManager {
- /**
- * 功能:生成国籍select表单下的option选项的字符串
- * @param value 设置为选中状态的option的值
- */
- public static String generateOptionString(long value) {
- List optionList = StartOnLoadService.dictionaryInfoMap.get("nationalMap");
- StringBuffer optionString = new StringBuffer();
- Country country = null;
- if(null != optionList) {
- for(int i = 0; i<optionList.size()&&optionList.get(i)!=null; i++) {
- country = (Country)optionList.get(i);
- if( value== country.getId()) {
- optionString.append("<option value='" + country.getId() + "' selected>" + country.getName() + "</option>");
- } else {
- optionString.append("<option value='" + country.getId() + "' >" + country.getName() + "</option>");
- }
- }
- }
- return optionString.toString();
- }
- }
JSP页面使用:
- <select name="fellow.nation" id="nation" style="width:110px;" >
- <%=OptionManager.generateOptionString(70007)%> <!-- 默认选中 为 "Z-中国"-->
- </select>
转载地址:http://ollevere.iteye.com/blog/1356352