001/** 002 * Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package com.mybatisflex.spring.boot; 017 018import com.mybatisflex.core.datasource.DataSourceBuilder; 019import com.mybatisflex.core.datasource.FlexDataSource; 020import org.apache.ibatis.session.SqlSessionFactory; 021import org.mybatis.spring.SqlSessionFactoryBean; 022import org.springframework.boot.autoconfigure.AutoConfigureBefore; 023import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; 024import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; 025import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; 026import org.springframework.boot.context.properties.EnableConfigurationProperties; 027import org.springframework.context.annotation.Bean; 028 029import javax.sql.DataSource; 030import java.util.Map; 031 032 033/** 034 * 多数据源的配置支持 035 */ 036@org.springframework.context.annotation.Configuration(proxyBeanMethods = false) 037@ConditionalOnClass({SqlSessionFactory.class, SqlSessionFactoryBean.class}) 038@ConditionalOnMybatisFlexDatasource() 039@EnableConfigurationProperties(MybatisFlexProperties.class) 040@AutoConfigureBefore({DataSourceAutoConfiguration.class}) 041public class MultiDataSourceAutoConfiguration { 042 043 private Map<String, Map<String, String>> dataSourceProperties; 044 045 046 public MultiDataSourceAutoConfiguration(MybatisFlexProperties properties) { 047 dataSourceProperties = properties.getDatasource(); 048 } 049 050 051 @Bean 052 @ConditionalOnMissingBean 053 public DataSource dataSource() { 054 055 FlexDataSource flexDataSource = null; 056 057 if (dataSourceProperties != null && !dataSourceProperties.isEmpty()) { 058 for (String key : dataSourceProperties.keySet()) { 059 DataSource dataSource = new DataSourceBuilder(dataSourceProperties.get(key)).build(); 060 if (flexDataSource == null) { 061 flexDataSource = new FlexDataSource(key, dataSource); 062 } else { 063 flexDataSource.addDataSource(key, dataSource); 064 } 065 } 066 } 067 068 return flexDataSource; 069 } 070 071 072}