搜尋
首頁Javajava教程深入理解spring多資料來源配置

專案中我們經常會遇到多重資料來源的問題,尤其是資料同步或定時任務等項目更是如此。多重資料來源讓人最頭痛的,不是配置多個資料來源,而是如何能靈活動態的切換資料來源。例如在一個spring和hibernate的框架的專案中,我們在spring配置中往往是配置一個dataSource來連接資料庫,然後綁定給sessionFactory,在dao層程式碼中再指定sessionFactory來進行資料庫操作。

深入理解spring多資料來源配置

如上圖所示,每一塊都是指定綁死的,如果是多個資料來源,也只能是下圖中那種方式。

深入理解spring多資料來源配置

可看出在Dao層程式碼中寫死了兩個SessionFactory,這樣日後如果再多一個資料來源,還要改程式碼加入一個SessionFactory,顯然這並不符合開閉原則。

那麼正確的做法應該是

深入理解spring多資料來源配置

程式碼如下:

1. applicationContext.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:aop="http://www.springframework.org/schema/aop"
  xmlns:cache="http://www.springframework.org/schema/cache"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
  xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang"
  xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm"
  xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task"
  xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
  http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd  
  http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd  
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd  
  http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd  
  http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd  
  http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.1.xsd  
  http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.1.xsd  
  http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd  
  http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd  
  http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd  
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd  
  http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd"> 
  
  <context:annotation-config /> 
  
  <context:component-scan base-package="com"></context:component-scan> 
  
  <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="locations"> 
      <list> 
        <value>classpath:com/resource/config.properties</value> 
      </list> 
    </property> 
  </bean> 
  
  <bean id="dataSourceOne" class="com.mchange.v2.c3p0.ComboPooledDataSource"
    destroy-method="close"> 
    <property name="driverClass" value="${dbOne.jdbc.driverClass}" /> 
    <property name="jdbcUrl" value="${dbOne.jdbc.url}" /> 
    <property name="user" value="${dbOne.jdbc.user}" /> 
    <property name="password" value="${dbOne.jdbc.password}" /> 
    <property name="initialPoolSize" value="${dbOne.jdbc.initialPoolSize}" /> 
    <property name="minPoolSize" value="${dbOne.jdbc.minPoolSize}" /> 
    <property name="maxPoolSize" value="${dbOne.jdbc.maxPoolSize}" /> 
  </bean> 
  
  <bean id="dataSourceTwo" class="com.mchange.v2.c3p0.ComboPooledDataSource"
    destroy-method="close"> 
    <property name="driverClass" value="${dbTwo.jdbc.driverClass}" /> 
    <property name="jdbcUrl" value="${dbTwo.jdbc.url}" /> 
    <property name="user" value="${dbTwo.jdbc.user}" /> 
    <property name="password" value="${dbTwo.jdbc.password}" /> 
    <property name="initialPoolSize" value="${dbTwo.jdbc.initialPoolSize}" /> 
    <property name="minPoolSize" value="${dbTwo.jdbc.minPoolSize}" /> 
    <property name="maxPoolSize" value="${dbTwo.jdbc.maxPoolSize}" /> 
  </bean> 
  
  <bean id="dynamicDataSource" class="com.core.DynamicDataSource"> 
    <property name="targetDataSources"> 
      <map key-type="java.lang.String"> 
        <entry value-ref="dataSourceOne" key="dataSourceOne"></entry> 
        <entry value-ref="dataSourceTwo" key="dataSourceTwo"></entry> 
      </map> 
    </property> 
    <property name="defaultTargetDataSource" ref="dataSourceOne"> 
    </property> 
  </bean> 
  
  <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
    <property name="dataSource" ref="dynamicDataSource" /> 
    <property name="hibernateProperties"> 
      <props> 
        <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> 
        <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop> 
        <prop key="hibernate.show_sql">false</prop> 
        <prop key="hibernate.format_sql">true</prop> 
        <prop key="hbm2ddl.auto">create</prop> 
      </props> 
    </property> 
    <property name="packagesToScan"> 
      <list> 
        <value>com.po</value> 
      </list> 
    </property> 
  </bean> 
  
  <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
    <property name="sessionFactory" ref="sessionFactory" /> 
  </bean> 
  
  <aop:config> 
    <aop:pointcut id="transactionPointCut" expression="execution(* com.dao..*.*(..))" /> 
    <aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointCut" /> 
  </aop:config> 
  
  <tx:advice id="txAdvice" transaction-manager="transactionManager"> 
    <tx:attributes> 
      <tx:method name="add*" propagation="REQUIRED" /> 
      <tx:method name="save*" propagation="REQUIRED" /> 
      <tx:method name="update*" propagation="REQUIRED" /> 
      <tx:method name="delete*" propagation="REQUIRED" /> 
      <tx:method name="*" read-only="true" /> 
    </tx:attributes> 
  </tx:advice> 
  
  <aop:config> 
    <aop:aspect id="dataSourceAspect" ref="dataSourceInterceptor"> 
      <aop:pointcut id="daoOne" expression="execution(* com.dao.one.*.*(..))" /> 
      <aop:pointcut id="daoTwo" expression="execution(* com.dao.two.*.*(..))" /> 
      <aop:before pointcut-ref="daoOne" method="setdataSourceOne" /> 
      <aop:before pointcut-ref="daoTwo" method="setdataSourceTwo" /> 
    </aop:aspect> 
  </aop:config> 
</beans>

2. DynamicDataSource. applicationContext.xml

package com.core; 
  
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; 
  
public class DynamicDataSource extends AbstractRoutingDataSource{ 
  
  @Override
  protected Object determineCurrentLookupKey() { 
    return DatabaseContextHolder.getCustomerType();  
  } 
  
}

2. DynamicDataSource.classclasso3. .class

package com.core; 
  
public class DatabaseContextHolder { 
  
  private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); 
  
  public static void setCustomerType(String customerType) { 
    contextHolder.set(customerType); 
  } 
  
  public static String getCustomerType() { 
    return contextHolder.get(); 
  } 
  
  public static void clearCustomerType() { 
    contextHolder.remove(); 
  } 
}

5. po實體類別

package com.core; 
  
import org.aspectj.lang.JoinPoint; 
import org.springframework.stereotype.Component; 
  
@Component
public class DataSourceInterceptor { 
  
  public void setdataSourceOne(JoinPoint jp) { 
    DatabaseContextHolder.setCustomerType("dataSourceOne"); 
  } 
    
  public void setdataSourceTwo(JoinPoint jp) { 
    DatabaseContextHolder.setCustomerType("dataSourceTwo"); 
  } 
}
package com.po; 
  
import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.Id; 
import javax.persistence.Table; 
  
@Entity
@Table(name = "BTSF_BRAND", schema = "hotel") 
public class Brand { 
  
  private String id; 
  private String names; 
  private String url; 
  
  @Id
  @Column(name = "ID", unique = true, nullable = false, length = 10) 
  public String getId() { 
    return this.id; 
  } 
  
  public void setId(String id) { 
    this.id = id; 
  } 
  
  @Column(name = "NAMES", nullable = false, length = 50) 
  public String getNames() { 
    return this.names; 
  } 
  
  public void setNames(String names) { 
    this.names = names; 
  } 
  
  @Column(name = "URL", length = 200) 
  public String getUrl() { 
    return this.url; 
  } 
  
  public void setUrl(String url) { 
    this.url = url; 
  } 
}

6. BrandDaoImpl.class

package com.po;  
import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.Id; 
import javax.persistence.Table; 
  
@Entity
@Table(name = "CITY", schema = "car") 
public class City { 
  
  private Integer id; 
    
  private String name; 
  
  @Id
  @Column(name = "ID", unique = true, nullable = false) 
  public Integer getId() { 
    return id; 
  } 
  
  public void setId(Integer id) { 
    this.id = id; 
  } 
  
  @Column(name = "NAMES", nullable = false, length = 50) 
  public String getName() { 
    return name; 
  } 
  
  public void setName(String name) { 
    this.name = name; 
  } 
}

7. CityDaoImpl.class

package com.dao.one; 
  
import java.util.List; 
  
import javax.annotation.Resource; 
  
import org.hibernate.Query; 
import org.hibernate.SessionFactory; 
import org.springframework.stereotype.Repository; 
  
import com.po.Brand; 
  
@Repository
public class BrandDaoImpl implements IBrandDao { 
  
  @Resource
  protected SessionFactory sessionFactory; 
  
  @SuppressWarnings("unchecked") 
  @Override
  public List<Brand> findAll() { 
    String hql = "from Brand"; 
    Query query = sessionFactory.getCurrentSession().createQuery(hql); 
    return query.list(); 
  } 
}

   

利用aop,達到動態變更資料來源的目的。當需要增加資料來源的時候,我們只需要在applicationContext設定檔中新增aop配置,新建個DataSourceInterceptor即可。而不需要更改任何程式碼。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持PHP中文網。

更多深入理解spring多資料來源配置相關文章請關注PHP中文網!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
JVM如何促進Java的'寫作一次,在任何地方運行”(WORA)功能?JVM如何促進Java的'寫作一次,在任何地方運行”(WORA)功能?May 02, 2025 am 12:25 AM

JVM通過字節碼解釋、平台無關的API和動態類加載實現Java的WORA特性:1.字節碼被解釋為機器碼,確保跨平台運行;2.標準API抽像操作系統差異;3.類在運行時動態加載,保證一致性。

Java的較新版本如何解決平台特定問題?Java的較新版本如何解決平台特定問題?May 02, 2025 am 12:18 AM

Java的最新版本通過JVM優化、標準庫改進和第三方庫支持有效解決平台特定問題。 1)JVM優化,如Java11的ZGC提升了垃圾回收性能。 2)標準庫改進,如Java9的模塊系統減少平台相關問題。 3)第三方庫提供平台優化版本,如OpenCV。

說明JVM執行的字節碼驗證的過程。說明JVM執行的字節碼驗證的過程。May 02, 2025 am 12:18 AM

JVM的字節碼驗證過程包括四個關鍵步驟:1)檢查類文件格式是否符合規範,2)驗證字節碼指令的有效性和正確性,3)進行數據流分析確保類型安全,4)平衡驗證的徹底性與性能。通過這些步驟,JVM確保只有安全、正確的字節碼被執行,從而保護程序的完整性和安全性。

平台獨立性如何簡化Java應用程序的部署?平台獨立性如何簡化Java應用程序的部署?May 02, 2025 am 12:15 AM

Java'splatFormIndepentEncealLowsApplicationStorunonAnyOperatingsystemwithajvm.1)singleCodeBase:writeandeandcompileonceforallplatforms.2)easileupdates:updatebybytecodeforsimultanane deployment.3)testOnOneOnePlatForforurouniverSalpeforuluniverSalpehavior formafforulululyiversalivernave.444.44.444

Java的平台獨立性如何隨著時間的流逝而發展?Java的平台獨立性如何隨著時間的流逝而發展?May 02, 2025 am 12:12 AM

Java的平台獨立性通過JVM、JIT編譯、標準化、泛型、lambda表達式和ProjectPanama等技術不斷增強。自1990年代以來,Java從基本的JVM演進到高性能的現代JVM,確保了代碼在不同平台的一致性和高效性。

在Java應用程序中緩解平台特定問題的策略是什麼?在Java應用程序中緩解平台特定問題的策略是什麼?May 01, 2025 am 12:20 AM

Java如何緩解平台特定的問題? Java通過JVM和標準庫來實現平台無關性。 1)使用字節碼和JVM抽像操作系統差異;2)標準庫提供跨平台API,如Paths類處理文件路徑,Charset類處理字符編碼;3)實際項目中使用配置文件和多平台測試來優化和調試。

Java的平台獨立性與微服務體系結構之間有什麼關係?Java的平台獨立性與微服務體系結構之間有什麼關係?May 01, 2025 am 12:16 AM

java'splatformentenceenhancesenhancesmicroservicesharchitecture byferingDeploymentFlexible,一致性,可伸縮性和便攜性。 1)DeploymentFlexibilityAllowsibilityAllowsOllowsOllowSorlowsOllowsOllowsOllowSeStorunonAnyPlatformwithajvM.2)penterencyCrossServAccAcrossServAcrossServiCessImplifififiesDeevelopmentandeDe

GRAALVM與Java的平台獨立目標有何關係?GRAALVM與Java的平台獨立目標有何關係?May 01, 2025 am 12:14 AM

GraalVM通過三種方式增強了Java的平台獨立性:1.跨語言互操作,允許Java與其他語言無縫互操作;2.獨立的運行時環境,通過GraalVMNativeImage將Java程序編譯成本地可執行文件;3.性能優化,Graal編譯器生成高效的機器碼,提升Java程序的性能和一致性。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器