`
awed
  • 浏览: 34036 次
  • 性别: Icon_minigender_1
  • 来自: 珠海
社区版块
存档分类
最新评论

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

    博客分类:
  • j2ee
阅读更多

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

自定义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;
    }

 

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

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics