·您现在的位置: 云翼网络 >> 文章中心 >> 网站建设 >> 网站建设问答 >> Spring双数据库配置

Spring双数据库配置

作者:佚名      网站建设问答编辑:admin      更新时间:2022-07-23

有时候我们可能在一个项目中使用两个数据库,为了实现使用两个或多个数据库的功能,我们需要在Spring中配置相关信息。

首先是添加配置文件conf.properties:

<bean id=“propertyConfigurer”class=“org.springframework.beans.factory.config.PropertyPlaceholderConfigurer”>

 <property name=“locations”>

<list>

 <value>classpath:config.properties</value>

</list>

</property>

</bean>

其次是添加数据源(${...}对应的是conf.properties中的配置信息)

<!--对应数据A的数据源-->

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

<!--对应数据库B的数据源-->

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

之后是添加对应的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>

在项目中的dao层有时会出现这样的配置信息:

<bean id = “XDao” class = “xxx.xxx.xDaoImpl”>

<property name=“sessionFactory” ref=“sessionFactory”></property>

</bean>

为了实现使用两个不同的数据库,可以改成:

<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数据库的DAO--></span> <bean id = “XDao” class = “xxx.xxx.xDaoImpl”>

<property name=“sessionFactory” ref=“sessionFactory_A”></property>

</bean>

<!--使用B数据库的DAO-->

<bean id = “XDao” class = “xxx.xxx.xDaoImpl”>

<property name=“sessionFactory” ref=“sessionFactory_B”></property>

</bean>

这样就能实现双数据库了。

原文链接:http://my.oschina.net/u/241670/blog/80148