Spring怎样高效的配置多套数据源

2025-03-24 11:10:30
推荐回答(1个)
回答1:

1、首先配置多个datasource


destroy-method="close">






destroy-method="close">






2、写一个DynamicDataSource类继承AbstractRoutingDataSource,并实现determineCurrentLookupKey方法

?
public class DynamicDataSource extends AbstractRoutingDataSource {
@SuppressWarnings("unused")
private Log logger = LogFactory.getLog(getClass());

@Override
protected Object determineCurrentLookupKey() {
return DbContextHolder.getDbType();
}
}

public class DbContextHolder {
@SuppressWarnings("rawtypes")

private static final ThreadLocal contextHolder = new ThreadLocal();

@SuppressWarnings("unchecked")
public static void setDbType(String dbType) {
contextHolder.set(dbType);
}

public static String getDbType() {
return (String) contextHolder.get();
}

public static void clearDbType() {
contextHolder.remove();
}
}

3. 配置动态数据源













4.使用动态数据源(hibernate)

class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">


















org.hibernate.dialect.Oracle10gDialect


true


auto

true

false

org.hibernate.cache.EhCacheProvider

false





使用Hibernate时的事务管理配置示例:


< property name="sessionFactory" ref="sessionFactory" />
bean>