首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

Spring利用沿袭DelegatingDataSource实现多数据源切换

2012-11-05 
Spring利用继承DelegatingDataSource实现多数据源切换根据用户所在的区域切换到自己区域的数据源,自定义Da

Spring利用继承DelegatingDataSource实现多数据源切换

根据用户所在的区域切换到自己区域的数据源,

自定义DataSource继承org.springframework.jdbc.datasource.DelegatingDataSource并且重写

?public Connection getConnection() throws SQLException方法

 public Connection getConnection() throws SQLException {    AgilityUserBean userBean = ThreadContext.getUser();    if(userBean != null){System.out.println("the system will user " + dataSourceName + userBean.getLocale() + " dataSource");ds = ApplicationContext.getInstance().getBean(dataSourceName + userBean.getLocale());    if(ds == null){    throw new SQLException("can't find the dataSource for this region.");    }    setTargetDataSource((DataSource)ds);    }else{    System.out.println("System use default dataSource " + dataSourceName);    }        Assert.state(getTargetDataSource() != null, "targetDataSource is required");        Connection con = null;        try {            con = getTargetDataSource().getConnection();        } catch (SQLException e) {            logger.error("Error occured during connection request. Thread name = " +                    Thread.currentThread().getName());            logger.error("Listing binded to thread resources...");            throw e;        }        return con;    }

?

经过简单的验证可行,不知道这样是否完全正确,希望大家拍砖!

?

?

热点排行