<bean id="dataSource" class="com.chnedu.common.util.MultiDataSource">
<property name="dataSource" ref="dataSource_a"/><!-- 默认连接数据库a -->
</bean>
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class MultiDataSource implements DataSource,ApplicationContextAware{
private ApplicationContext applicationContext=null;
private DataSource dataSource = null;
@Override
public PrintWriter getLogWriter() throws SQLException {
return getDataSource().getLogWriter();
}
@Override
public int getLoginTimeout() throws SQLException {
return getDataSource().getLoginTimeout();
}
@Override
public void setLogWriter(PrintWriter arg0) throws SQLException {
getDataSource().setLogWriter(arg0);
}
@Override
public void setLoginTimeout(int arg0) throws SQLException {
getDataSource().setLoginTimeout(arg0);
}
@Override
public boolean isWrapperFor(Class<?> arg0) throws SQLException {
return getDataSource().isWrapperFor(arg0);
}
@Override
public <T> T unwrap(Class<T> arg0) throws SQLException {
return getDataSource().unwrap(arg0);
}
@Override
public void setApplicationContext(ApplicationContext arg0)
throws BeansException {
this.applicationContext = arg0;
}
@Override
public Connection getConnection() throws SQLException {
return getDataSource().getConnection();
}
@Override
public Connection getConnection(String arg0, String arg1)
throws SQLException {
return getDataSource().getConnection(arg0, arg1);
}
public DataSource getDataSource() {
//根据session 中变量更换数据源
Object siteId = StrutsUtil.getSession().get( Constants.SESSION_SITE_ID );
if(siteId==null || "".equals( siteId)){
return dataSource;
}else if( Constants.ACC_SITE_ID.equals( siteId)){
dataSource = (DataSource) this.applicationContext.getBean("dataSource_a");
}else {
dataSource = (DataSource) this.applicationContext.getBean( "dataSource_b") ;
}
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
}