廢話不多說,關鍵程式碼如下圖:
1. 程式碼: DbContextHolder
public class DbContextHolder { //线程安全的ThreadLocal private static final ThreadLocalcontextHolder = 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(); } }
2. 代碼: DynamicData
4. 程式碼:main方法import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class DynamicDataSource extends AbstractRoutingDataSource { @Override public Object determineCurrentLookupKey() { return DbContextHolder.getDbType(); } }