配置application.xml的dataSource:
<bean id=
"aTestDataSource"
class
=
"org.springframework.jdbc.datasource.DriverManagerDataSource"
>
<property name=
"driverClassName"
value=
"com.mysql.jdbc.Driver"
/>
<property name=
"url"
value=
"jdbc:mysql://Ip:3306/tms_db?useUnicode=true&characterEncoding=UTF-8"
/>
<property name=
"username"
value=
"**"
/>
<property name=
"password"
value=
"**"
/>
</bean>
<bean id=
"bTestDataSource"
class
=
"org.springframework.jdbc.datasource.DriverManagerDataSource"
>
<property name=
"driverClassName"
value=
"com.microsoft.jdbc.sqlserver.SQLServerDriver"
/>
<property name=
"url"
value=
"jdbc:microsoft:sqlserver://Ip:1433;DatabaseName=***"
/>
<property name=
"username"
value=
"**"
/>
<property name=
"password"
value=
"*****"
/>
</bean>
<bean id=
"dataSource"
class
=
"util.DynamicDataSource"
>
<property name=
"targetDataSources"
>
<map key-type=
"java.lang.String"
>
<entry key=
"aTestDataSource"
value-ref=
"aTestDataSource"
/>
<entry key=
"bTestDataSource"
value-ref=
"bTestDataSource"
/>
</map>
</property>
<property name=
"defaultTargetDataSource"
ref=
"aTestDataSource"
/>
</bean>
2. [代码]配置DynamicDataSource 和DbContextHolder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
public
class
DynamicDataSource
extends
AbstractRoutingDataSource {
@Override
protected
Object determineCurrentLookupKey() {
// TODO Auto-generated method stub
return
DbContextHolder.getDbType();
}
public
<T> T unwrap(Class<T> iface)
throws
SQLException {
// TODO Auto-generated method stub
return
null
;
}
public
boolean
isWrapperFor(Class<?> iface)
throws
SQLException {
// TODO Auto-generated method stub
return
false
;
}
}
public
class
DbContextHolder {
private
static
final
ThreadLocal contextHolder =
new
ThreadLocal();
public
static
void
setDbType(String dbType)
{
contextHolder.set(dbType);
}
public
static
String getDbType()
{
String str=(String) contextHolder.get();
if
(
null
==str ||
""
.equals(str))
str=
"1"
;
return
str;
}
public
static
void
clearDbType()
{
contextHolder.remove();
}
}
|
3. [代码]在contorller内切换数据源
1
2
3
4
5
6
|
DbContextHolder.setDbType(
"bTestDataSource"
);
//此处切换数据源
System.out.println(DbContextHolder.getDbType());
List list = orderService.***();
DbContextHolder.setDbType(
"aTestDataSource"
);
//切换回来默认的数据源
System.out.println(DbContextHolder.getDbType());
注:此处最好使用spring aop切入。
|