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连接数据库




猜你喜欢

转载自blog.csdn.net/qq_27339781/article/details/80341056