spring初始化访问数据库,加载数据

背景:

在实际开发中,通常服务器都很多,每台服务器上的应用都需要配置参数,如果有修改或者变动就会很麻烦,每台服务器都需要改一次。所以有必要把一些参数配置到数据库里,这样方便查看和管理,这就需要初始化时加载数据库

方案一:

(1)写一个类,实现spring中的InitializingBean, ServletContextAware 接口,让后通过IOC交给Spring管理

import java.util.List;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.ServletContextAware;

import com.jinrui.pojo.SysPropPojo;
import com.jinrui.service.SysPropService;

public class InitDataListener implements InitializingBean, ServletContextAware{
	@Autowired
	SysPropService sysPropService;
	
	/**
	 * 读取数据库的数据,将其放入application中
	 */
	@Override
	public void setServletContext(ServletContext application) {		
		List<SysPropPojo>  propList = sysPropService.getSysProps();
		for (int i = 0; i < propList.size(); i++) {
			String key = propList.get(i).getKey();
			String value = propList.get(i).getValue();
			application.setAttribute(key, value);
			
		}					
	}
	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub
		
	}
}

注:

ServletContext也是和session一样像一张表,分为属性、值

    方法:

      添加属性:setAttribute(String name,Object obj);

      得到值:getAttribute(String name);

      删除属性:removeAttribute(String name); 



    生命周期

      ServletContext中的属性的生命周期从创建开始,到服务器关闭而结束

(2)在applicationContent中

<!-- spring系统启动以后,会先加载该类 -->

 <bean class="com.xiong.application.InitDataListener"></bean> 

(3)测试

        @Autowired

protected ServletContext  application;

        public String getSysProp(String key){
return  (String) application.getAttribute(key);
}

方案二:

        监听器或拦截器实现,不过要JDBC连接数据库




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值