使用Spring动态修改DataSource
最早发表时间:2008-12-03
?
??? 我们现在在做的这个项目使用了经典的框架Spring 2.0.2,开发环境是Eclipse 3.4。
??? 由于运行的程序有可能需要使用不同的数据库服务器,所以需要在程序启动的时候,根据某个配置文件来判断正要使用的数据库类型和连接方式。
??? 我编写了一个工具类用于获取Spring的配置文件并且初始化Spring工作的上下文环境,示例代码如下:
/** * Updated at 上午11:49:55, on 2008-12-3<br> * 获取Spring的配置信息来初始化Spring的上下文环境信息 * * @return 返回Spring的上下文环境配置 * @author Guokai */ public static ApplicationContext getAppcxt () { if (appcxt == null) { String[] url = new String[] { "beanRefFactory.xml", "dataAccessContext.xml", "config/spring/*.xml" }; appcxt = new ClassPathXmlApplicationContext(url); // 通过配置文件获取联网方式和数据源的配置信息 initSubmitTypeAndConnectionType(); } return appcxt; } /** * Updated at 上午11:49:26, on 2008-12-3<br> * 通过配置文件获取联网方式和数据源的配置信息 * * @author Guokai */ private static void initSubmitTypeAndConnectionType () { // 获取配置文件 InputStream configInStream = SpringHelper.class.getResourceAsStream("/config.properties"); Properties properties = new Properties(); try { properties.load(configInStream); } catch (IOException e) { e.printStackTrace(); } // 根据数据库连接配置来设置数据源对象 BasicDataSource basicDS = (BasicDataSource) appcxt.getBean("dataSource"); try { // 这里需要先关闭数据源,才可以使新的数据源设置生效 basicDS.close(); } catch (SQLException e) { log.warn("关闭从Spring获取的数据源时出现异常!", e); } basicDS.setDriverClassName(properties.getProperty("jdbc.driverClassName")); basicDS.setUrl(properties.getProperty("jdbc.url")); basicDS.setUsername(properties.getProperty("jdbc.username")); basicDS.setPassword(properties.getProperty("jdbc.password")); basicDS.setMaxWait(Long.parseLong(properties.getProperty("jdbc.maxWait"))); }
?
??? 通过调用工具类的getAppcxt()方法来获取Spring的运行环境对象,在初始化Spring运行环境对象的过程中从项目的src目录下的config.properties文件当中读取数据源配置,从而创建连接数据库的数据源对象。
还有以下几点需要说明:
1. 这里需要注意的是:在获取dataSource之后,需要将这个数据源首先关闭一下,因为有可能数据源已经处于打开的状态,如果不关闭的话,即使改变数据源的配置,之前创建的数据库连接还是根据旧有配置创建的那些连接对象;
2. 项目中 Spring 配置的数据源的 id 为 dataSource,类型为 org.apache.commons.dbcp.BasicDataSource。