1.配置xml文件
applicationContext.xml
2.编写动态连接的接口:
public class DynamicDataSource extends AbstractRoutingDataSource {
private Map _targetDataSources;
@Override
protected Object determineCurrentLookupKey() {
return DataSourceContextHolder.getDataSource();
}
public void setTargetDataSources(Map targetDataSources) {
this._targetDataSources = targetDataSources;
super.setTargetDataSources(targetDataSources);
afterPropertiesSet();
}
public String getDbtype(String key) {
String driver = ((BasicDataSource) _targetDataSources.get(key))
.getDriverClassName();
if ("oracle.jdbc.driver.OracleDriver".equals(driver)) {
return "oracle";
} else if ("com.mysql.jdbc.Driver".equals(driver)) {
return "mysql";
}
return null;
}
public void addTargetDataSource(String key, DataSource dataSource) {
_targetDataSources.put(key, dataSource);
this.setTargetDataSources(_targetDataSources);
}
public static DataSource createDataSource(String driverClassName,
String url, String username, String password) {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setTestWhileIdle(true);
if ("oracle.jdbc.driver.OracleDriver".equals(driverClassName)) {
dataSource.setValidationQuery("SELECT 1 FROM DUAL");
} else if ("com.mysql.jdbc.Driver".equals(driverClassName)) {
dataSource.setValidationQuery("SELECT NOW()");
}
return dataSource;
}
}3.测试:
DynamicDataSource dynamicDataSource = ApplicationUtil
.getBean(DynamicDataSource.class);
BasicDataSource dataSource = DynamicDataSource.createDataSource(driverClassName,url,userName,password)
dynamicDataSource.addTargetDataSource("dbkey", dataSource );
DataSourceContextHolder.setDataSource("dbkey");
// 通过以上语句可以将数据库连接配置修改为当前设置的
//执行自己的DAO方法
DataSourceContextHolder.clearDataSource();//恢复数据库的配置为applicationContext.xml默认的配置