配置applicationContext.xml
<!-- 将多个配置文件读取到容器中,交给Spring管理 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:global.properties</value>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
<!--master 配置数据源 -->
<bean id="masterDataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="driverClassName">
<value>${master.jdbc.driverClassName}</value>
</property>
<property name="url">
<value>${master.jdbc.url}</value>
</property>
<property name="username">
<value>${master.jdbc.username}</value>
</property>
<property name="password">
<value>${master.jdbc.password}</value>
</property>
...
</bean>
<!--slave 配置数据源 -->
<bean id="slaveDataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="driverClassName">
<value>${slave.jdbc.driverClassName}</value>
</property>
<property name="url">
<value>${slave.jdbc.url}</value>
</property>
<property name="username">
<value>${slave.jdbc.username}</value>
</property>
<property name="password">
<value>${slave.jdbc.password}</value>
</property>
...
</bean>
<bean id="dataSource" class="cn.mayongfa.service.imp.DynamicDataSource">
<property name="targetDataSources">
<map>
<entry key="slave" value-ref="slaveDataSource" />
</map>
</property>
<property name="defaultTargetDataSource" ref="masterDataSource" />
</bean>
<!-- 配置Jdbc模板 -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource" />
<!-- 数据源切换类 -->
<bean id="dataSourceChoose" class="cn.mayongfa.interceptor.DataSourceChoose" />
<!-- 通过AOP配置提供事务增强,让service包下所有Bean的所有方法拥有事务 -->
...
时间: 2024-12-16 16:13:59