spring mvcマルチデータソースの切り替えを解決し、事務制御の問題をサポートしていません。


一つのプロジェクトには二つのデータベース、OracleとMysqlが必要で、それぞれのブログを参考にしてこの機能を実現します。書いてみたら、元の仕事は失効しました。行きます。
spring-mybatis.xml配置

<bean id="configReader" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
  <property name="locations">
   <list>
    <value>classpath:spring/db.properties</value>
   </list>
  </property>
  <property name="ignoreResourceNotFound" value="true"/>
 </bean>

 <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  <property name="driverClass" value="${jdbc.oracle.DriverClassName}"></property>
  <property name="jdbcUrl" value="${jdbc.oracle.Url}"></property>
  <property name="user" value="${jdbc.oracle.UserName}"></property>
  <property name="password" value="${jdbc.oracle.UserPassword}"></property>

  <property name="acquireIncrement" value="5"></property>
  <property name="initialPoolSize" value="5"></property>
  <property name="maxIdleTime" value="60"></property>
  <property name="maxPoolSize" value="100"></property>
  <property name="minPoolSize" value="5"></property>
 </bean>


 <!--      :MySQL start -->
 <bean name="mySqlDataSource" class="com.alibaba.druid.pool.DruidDataSource"
   init-method="init" destroy-method="close">
  <property name="driverClassName" value="${jdbc.mysql.DriverClassName}"/>
  <property name="url" value="${jdbc.mysql.Url}"/>
  <property name="username" value="${jdbc.mysql.UserName}"/>
  <property name="password" value="${jdbc.mysql.UserPassword}"/>

  <!--         -->
  <property name="initialSize" value="5"/>
  <!--             -->
  <property name="maxActive" value="30"/>
  <!--         -->
  <property name="minIdle" value="2"/>
  <!--            -->
  <property name="maxWait" value="300"/>

  <property name="validationQuery" value="SELECT 1"/>
  <property name="testOnBorrow" value="false"/>
  <property name="testOnReturn" value="false"/>
  <property name="testWhileIdle" value="true"/>

  <!--              ,           ,      -->
  <property name="timeBetweenEvictionRunsMillis" value="10000"/>
  <!--                 ,      -->
  <property name="minEvictableIdleTimeMillis" value="30000"/>

  <!--   removeAbandoned   -->
  <property name="removeAbandoned" value="true"/>
  <!-- 1800 ,   30   -->
  <property name="removeAbandonedTimeout" value="1800"/>
  <!--   abanded          -->
  <property name="logAbandoned" value="true"/>

  <!--       -->
  <property name="filters" value="stat"/>
 </bean>


 <bean id="multipleDataSource" class="com.we.database.MultipleDataSource">
  <property name="defaultTargetDataSource" ref="dataSource"/>
  <property name="targetDataSources">
   <map>
    <entry key="oracleDataSource" value-ref="dataSource"/>
    <entry key="mySqlDataSource" value-ref="mySqlDataSource"/>
   </map>
  </property>
 </bean>

 <!-- oracle myBatis file -->
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="multipleDataSource"/>
  <!--<property name="configLocation" value="classpath:configuration.xml" /> -->
  <property name="mapperLocations" value="classpath:com/we/dao/mapper/*.xml"/>
 </bean>

 <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="basePackage" value="com.we.dao"/>
  <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
 </bean>


 <!-- configure transaction -->
 <bean id="transactionManager"
   class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource"/>
 </bean>

 <!-- annotation transaction -->
 <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>


 <!-- interception transatcion -->
 <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
  <tx:attributes>
   <tx:method name="add*" propagation="REQUIRED"/>
  </tx:attributes>
 </tx:advice>

 <!--        aop -->
 <bean id="dataSourceAspect" class="com.we.database.DataSourceAspect"/>

 <aop:config>
  <aop:pointcut id="transactionPointcut" expression="execution(* com.wewe.licai.service..*Impl.*(..))"/>
  <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" order="2"/>

  <!--       ,           -->
  <aop:advisor pointcut-ref="transactionPointcut" advice-ref="dataSourceAspect" order="1" />
 </aop:config>
コメント切り替え、デフォルトはoracleデータソースを使用します。

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})

public @interface DataSource {
  String name() default DataSource.oracleDataSource;
  String mySqlDataSource = "mySqlDataSource";
  String oracleDataSource = "oracleDataSource";
}
注釈方式はデータソースの切り替えを実現し、注釈を検索し、注釈上のデータソースを交換し、クラスの注釈と方法の注釈をサポートする。

/**
 * Created by eastday on 2017/9/21.
 */
public class DataSourceAspect implements MethodBeforeAdvice,AfterReturningAdvice
{

 @Override
 public void afterReturning(Object returnValue, Method method,
        Object[] args, Object target) throws Throwable {

  MultipleDataSource.clearDataSource();
 }

 @Override
 public void before(Method method, Object[] args, Object target)
   throws Throwable {

  //         
  if(method.getDeclaringClass().isAnnotationPresent(DataSource.class) && !method.isAnnotationPresent(DataSource.class)) {

   DataSource datasource = method.getDeclaringClass().getAnnotation(DataSource.class);
   MultipleDataSource.setDataSource(datasource.name());

   //                
  } else if (method.isAnnotationPresent(DataSource.class)) {

   DataSource datasource = method.getAnnotation(DataSource.class);
   MultipleDataSource.setDataSource(datasource.name());
  }
  else
  {
   MultipleDataSource.setDataSource(DataSource.oracleDataSource);
  }
 }
}
AbstractRoutingDataSourceを継承してデータソースの切り替えを実現します。

public class MultipleDataSource extends AbstractRoutingDataSource {
 private static final ThreadLocal<String> dataSources = new InheritableThreadLocal<String>();

 public static void setDataSource(String dataSource) {
  dataSources.set(dataSource);
 }

 //     
 public static void clearDataSource() {
  dataSources.remove();
 }

 @Override
 protected Object determineCurrentLookupKey() {
  return dataSources.get();
 }
}
デモを使う

@DataSource(name = DataSource.mySqlDataSource)
public class ContentServiceImpl implements IContentService {

 @Autowired
 private IContentDao contentDao;

 @Override
 public Content queryOne(String type) {
  return contentDao.queryOne(type);
 }
}
以上のこの解決方法はspring mvc多データ源の切り替えです。事務コントロールに対応していない問題は小編集が皆さんに共有している内容です。参考にしてもらいたいです。皆さんも応援してください。