Spring雙數(shù)據(jù)庫(kù)配置
有時(shí)候我們可能在一個(gè)項(xiàng)目中使用兩個(gè)數(shù)據(jù)庫(kù),為了實(shí)現(xiàn)使用兩個(gè)或多個(gè)數(shù)據(jù)庫(kù)的功能,我們需要在Spring中配置相關(guān)信息。
首先是添加配置文件conf.properties
- <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <property name="locations">
- <list>
- <value>classpath:config.properties</value>
- </list>
- </property>
- </bean>
其次是添加數(shù)據(jù)源(${...}對(duì)應(yīng)的是conf.properties中的配置信息)
- <!--對(duì)應(yīng)數(shù)據(jù)A的數(shù)據(jù)源-->
- <bean id="dataSource_A" class="org.apache.commons.dbcp.BasicDataSource">
- <property name="driverClassName" value="${A.driver_class}" />
- <property name="url" value="${A.url}" />
- <property name="username" value="${A.username}" />
- <property name="password" value="${A.password}" />
- </bean>
- <!--對(duì)應(yīng)數(shù)據(jù)庫(kù)B的數(shù)據(jù)源-->
- <bean id="dataSource_B" class="org.apache.commons.dbcp.BasicDataSource">
- <property name="driverClassName" value="${B.driver_class}" />
- <property name="url" value="${B.url}" />
- <property name="username" value="${B.username}" />
- <property name="password" value="${B.password}" />
- </bean>
之后是添加對(duì)應(yīng)的sessionFactory:
- <!-- A的sessionFactory -->
- <bean id="sessionFactory_A" class="moretv.commons.spring.hibernate3.AnnotationSessionFactoryBean">
- <property name="dataSource" ref="dataSource_A"/>
- </bean>
- <!-- B的sessionFactory -->
- <bean id="sessionFactory_B" class="moretv.commons.spring.hibernate3.AnnotationSessionFactoryBean">
- <property name="dataSource" ref="dataSource_B"/>
- </bean>
在項(xiàng)目中的dao層有時(shí)會(huì)出現(xiàn)這樣的配置信息:
- <bean id = "XDao" class = "xxx.xxx.xDaoImpl">
- <property name="sessionFactory" ref="sessionFactory"></property>
- </bean>
為了實(shí)現(xiàn)使用兩個(gè)不同的數(shù)據(jù)庫(kù),可以改成
- <span style="font-family:'sans serif', tahoma, verdana, helvetica;font-size:13px;line-height:19px;white-space:normal;background-color:#ffffff;"> </span><span style="font-family:'sans serif', tahoma, verdana, helvetica;white-space:normal;background-color:#ffffff;"><!--使用A數(shù)據(jù)庫(kù)的DAO--></span> <bean id = "XDao" class = "xxx.xxx.xDaoImpl">
- <property name="sessionFactory" ref="sessionFactory_A"></property>
- </bean>
- <!--使用B數(shù)據(jù)庫(kù)的DAO-->
- <bean id = "XDao" class = "xxx.xxx.xDaoImpl">
- <property name="sessionFactory" ref="sessionFactory_B"></property>
- </bean>
這樣就能實(shí)現(xiàn)雙數(shù)據(jù)庫(kù)了。。。。