最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

深入理解spring多數(shù)據(jù)源配置

 更新時(shí)間:2017年01月06日 16:12:24   作者:wangpeng047  
項(xiàng)目中我們經(jīng)常會(huì)遇到多數(shù)據(jù)源的問(wèn)題,尤其是數(shù)據(jù)同步或定時(shí)任務(wù)等項(xiàng)目更是如此。本篇文章主要介紹了spring多數(shù)據(jù)源配置,有興趣的可以了解一下。

項(xiàng)目中我們經(jīng)常會(huì)遇到多數(shù)據(jù)源的問(wèn)題,尤其是數(shù)據(jù)同步或定時(shí)任務(wù)等項(xiàng)目更是如此。多數(shù)據(jù)源讓人最頭痛的,不是配置多個(gè)數(shù)據(jù)源,而是如何能靈活動(dòng)態(tài)的切換數(shù)據(jù)源。例如在一個(gè)spring和hibernate的框架的項(xiàng)目中,我們?cè)趕pring配置中往往是配置一個(gè)dataSource來(lái)連接數(shù)據(jù)庫(kù),然后綁定給sessionFactory,在dao層代碼中再指定sessionFactory來(lái)進(jìn)行數(shù)據(jù)庫(kù)操作。

正如上圖所示,每一塊都是指定綁死的,如果是多個(gè)數(shù)據(jù)源,也只能是下圖中那種方式。

 

可看出在Dao層代碼中寫(xiě)死了兩個(gè)SessionFactory,這樣日后如果再多一個(gè)數(shù)據(jù)源,還要改代碼添加一個(gè)SessionFactory,顯然這并不符合開(kāi)閉原則。

那么正確的做法應(yīng)該是

代碼如下:

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.class

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

3. DatabaseContextHolder.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(); 
  } 
} 

4. DataSourceInterceptor.class

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"); 
  } 
} 

5. po實(shí)體類(lèi)

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; 
  } 
} 
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; 
  } 
} 

6. BrandDaoImpl.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(); 
  } 
} 

7. CityDaoImpl.class

package com.dao.two; 
 
import java.util.List; 
 
import javax.annotation.Resource; 
 
import org.hibernate.Query; 
import org.hibernate.SessionFactory; 
import org.springframework.stereotype.Repository; 
 
import com.po.City; 
 
@Repository 
public class CityDaoImpl implements ICityDao { 
 
  @Resource 
  private SessionFactory sessionFactory; 
 
  @SuppressWarnings("unchecked") 
  @Override 
  public List<City> find() { 
    String hql = "from City"; 
    Query query = sessionFactory.getCurrentSession().createQuery(hql); 
    return query.list(); 
  } 
} 

8. DaoTest.class

package com.test; 
 
import java.util.List; 
 
import javax.annotation.Resource; 
 
import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.springframework.test.context.ContextConfiguration; 
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 
import org.springframework.test.context.transaction.TransactionConfiguration; 
 
import com.dao.one.IBrandDao; 
import com.dao.two.ICityDao; 
import com.po.Brand; 
import com.po.City; 
 
@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = "classpath:com/resource/applicationContext.xml") 
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false) 
public class DaoTest { 
 
  @Resource 
  private IBrandDao brandDao; 
 
  @Resource 
  private ICityDao cityDao; 
 
  @Test 
  public void testList() { 
    List<Brand> brands = brandDao.findAll(); 
    System.out.println(brands.size()); 
 
    List<City> cities = cityDao.find(); 
    System.out.println(cities.size()); 
  } 
} 

利用aop,達(dá)到動(dòng)態(tài)更改數(shù)據(jù)源的目的。當(dāng)需要增加數(shù)據(jù)源的時(shí)候,我們只需要在applicationContext配置文件中添加aop配置,新建個(gè)DataSourceInterceptor即可。而不需要更改任何代碼。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 如何優(yōu)雅的拋出Spring Boot注解的異常詳解

    如何優(yōu)雅的拋出Spring Boot注解的異常詳解

    這篇文章主要給大家介紹了關(guān)于如何優(yōu)雅的拋出Spring Boot注解的異常的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2018-12-12
  • Java Spring事務(wù)使用及驗(yàn)證過(guò)程詳解

    Java Spring事務(wù)使用及驗(yàn)證過(guò)程詳解

    這篇文章主要介紹了Java Spring事務(wù)使用及驗(yàn)證過(guò)程詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-12-12
  • Java GUI編程之貪吃蛇游戲簡(jiǎn)單實(shí)現(xiàn)方法【附demo源碼下載】

    Java GUI編程之貪吃蛇游戲簡(jiǎn)單實(shí)現(xiàn)方法【附demo源碼下載】

    這篇文章主要介紹了Java GUI編程之貪吃蛇游戲簡(jiǎn)單實(shí)現(xiàn)方法,詳細(xì)分析了貪吃蛇游戲的具體實(shí)現(xiàn)步驟與相關(guān)注意事項(xiàng),并附帶demo源碼供讀者下載參考,需要的朋友可以參考下
    2017-09-09
  • Springmvc返回html頁(yè)面問(wèn)題如何解決

    Springmvc返回html頁(yè)面問(wèn)題如何解決

    這篇文章主要介紹了Springmvc返回html頁(yè)面問(wèn)題如何解決,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-10-10
  • java如何在應(yīng)用代碼里捕獲線程堆棧

    java如何在應(yīng)用代碼里捕獲線程堆棧

    這篇文章主要為大家介紹了java如何在應(yīng)用代碼里捕獲線程堆棧實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-12-12
  • JavaWeb中的路徑問(wèn)題解讀

    JavaWeb中的路徑問(wèn)題解讀

    這篇文章主要介紹了JavaWeb中的路徑問(wèn)題解讀,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • 實(shí)例解析觀察者模式及其在Java設(shè)計(jì)模式開(kāi)發(fā)中的運(yùn)用

    實(shí)例解析觀察者模式及其在Java設(shè)計(jì)模式開(kāi)發(fā)中的運(yùn)用

    觀察者模式定義了一種一對(duì)多的依賴關(guān)系,讓多個(gè)觀察者對(duì)象同時(shí)監(jiān)聽(tīng)某一個(gè)主題對(duì)象,這個(gè)主題對(duì)象在狀態(tài)上發(fā)生變化時(shí),會(huì)通知所有觀察者對(duì)象,使它們能夠自動(dòng)更新自己.下面就以實(shí)例解析觀察者模式及其在Java設(shè)計(jì)模式開(kāi)發(fā)中的運(yùn)用
    2016-05-05
  • Mybatis之mapper接口多參數(shù)方式

    Mybatis之mapper接口多參數(shù)方式

    這篇文章主要介紹了Mybatis之mapper接口多參數(shù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-05-05
  • Java中的HashMap集合源碼詳細(xì)解讀

    Java中的HashMap集合源碼詳細(xì)解讀

    這篇文章主要介紹了Java中的HashMap集合源碼詳細(xì)解讀,hash表是一種數(shù)據(jù)結(jié)構(gòu),它擁有驚人的效率,它的時(shí)間復(fù)雜度低到接近O(1)這樣的常數(shù)級(jí),需要的朋友可以參考下
    2023-11-11
  • Intellij 下 mybatis 插件 MyBatisCodeHelperPro破解步驟詳解

    Intellij 下 mybatis 插件 MyBatisCodeHelperPro破解步驟詳解

    這篇文章主要介紹了Intellij 下 mybatis 插件 MyBatisCodeHelperPro破解步驟,本文分步驟給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-09-09

最新評(píng)論

台南县| 肇东市| 丹寨县| 元阳县| 门源| 郑州市| 汉中市| 山东省| 鸡泽县| 滦平县| 平利县| 渭源县| 福贡县| 秦安县| 昭通市| 双峰县| 海伦市| 漯河市| 浦北县| 枣阳市| 改则县| 巴彦县| 登封市| 怀安县| 阳谷县| 来宾市| 泾川县| 古交市| 海伦市| 霍林郭勒市| 景洪市| 五指山市| 顺义区| 吴桥县| 黄大仙区| 卓尼县| 讷河市| 亚东县| 沁阳市| 定南县| 湖州市|