文档详情

Springmvc动态多数据源配置手册.docx

发布:2017-08-09约3.95千字共4页下载文档
文本预览下载声明
Spring mvc动态多数据源配置手册本功能基于Spring MVC,拦截器实现Session控制。? ? ? ? 通过拦截器取得当前使用的Locale,然后通过Locale找到不同的数据源。? ? ? ? 首先,新建类DynamicDataSource,使其继承org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource并实现其determineCurrentLookupKey方法,并实现获取currentLookupKey的方法,代码如下所示:*/packagecom.gsww.jup.controller;importorg.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;/** * 动态数据源 * * * @date 2015-02-01 下午12:30:51 */publicclassDynamicDataSourceextendsAbstractRoutingDataSource {publicstaticfinal String DATA_SOURCE_A = dataSourceA;publicstaticfinal String DATA_SOURCE_B = dataSourceB;publicstaticfinal String DATA_SOURCE_C = dataSourceC;privatestaticfinalThreadLocalString contextHolder = newThreadLocalString();/** * * @date 2015-02-01 下午12:30:51 * @return the currentLookupKey */publicstatic String getCurrentLookupKey() {return (String) contextHolder.get();}/** * * @date 2015-02-01 下午19:10:08 * @paramcurrentLookupKey * the currentLookupKey to set */publicstaticvoidsetCurrentLookupKey(String currentLookupKey) {contextHolder.set(currentLookupKey);}/* * (non-Javadoc) * * @see * org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource# * determineCurrentLookupKey() */@Overrideprotected Object determineCurrentLookupKey() {returngetCurrentLookupKey();}}上述代码中的determineCurrentLookupKey方法取得一个字符串,该字符串将与配置文件中的相应字符串进行匹配以定位数据源,配置文件,即applicationContext-dynamicDataSource.xml文件中需要要如下代码:!--动态数据源 --beanid=dataSourceclass=com.gsww.jup.controller.DynamicDataSourcepropertyname=targetDataSourcesmapkey-type=java.lang.Stringentrykey=dataSourceAvalue-ref=dataSourceA/entrykey=dataSourceBvalue-ref=dataSourceB/entrykey=dataSourceCvalue-ref=dataSourceC//map/propertypropertyname=defaultTargetDataSourceref=dataSourceA//bean? determineCurrentLookupKey方法取得字符串后,将会与上述配置中的map.../map中的值对应,即当determineCurrentLookupKey方法取得值为en时,则数据源指向englishDataSource,当然,map中的value-ref对应的是你在applicationContext-dynamicDataSource.xml文件中配置的数据源,如下所述:!--创建dataSourceA:jdbc数据源 --beanid=dataSourceAclass=mon
显示全部
相似文档