小弟刚开始学习spring方面的内容,遇到一个问题,我在一个项目中涉及到很多的数据库,想在spring中配置多个数据源如何操作呢。我的配置文件是这样的 在我的application.properties 有
- Java code
jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=utf-8jdbc.url1=jdbc:mysql://localhost/test1?useUnicode=true&characterEncoding=utf-8jdbc.username=rootjdbc.password=123456hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
每当一个多一个数据库 我就在这个配置文件添加一个jdbc.url 命名为jdbc.url加一个数字名
在applicationContent.xml中
- Java code
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <!-- Connection Info --> <property name="driverClassName" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- Connection Pooling Info --> <property name="initialSize" value="5" /> <property name="maxActive" value="100" /> <property name="maxIdle" value="30" /> <property name="maxWait" value="1000" /> <property name="poolPreparedStatements" value="false" /> <property name="defaultAutoCommit" value="false" /> </bean>
这里<property name="url" value="${jdbc.url}" /> property name="url" 如何根据程序传递一个datasource标识去动态的获取url的value值呢。如何设置默认的动态url连接呢。请赐教!
------解决方案--------------------
给你一个我们用的:
context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
<jee:jndi-lookup id="mysqlds" jndi-name="java:comp/env/jdbc/mysqlds" />
<jee:jndi-lookup id="orads" jndi-name="java:comp/env/jdbc/orads" />
<bean id="dataSource" class="util.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="0" value-ref="mysqlds" />
<entry key="1" value-ref="orads" />
</map>
</property>
<property name="defaultTargetDataSource" ref="orads" />
</bean>
</beans>
package util;
public class DbContextHolder {
private static final ThreadLocal contextHolder = new ThreadLocal();
public static void setDbType(String dbType) {
contextHolder.set(dbType);
}
public static String getDbType() {
return (String) contextHolder.get();
}
public static void clearDbType() {
contextHolder.remove();
}
}
package util;
import java.sql.SQLException;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;