matrix.boot.jdbc.config.DynamicDataSourceAutoConfiguration Maven / Gradle / Ivy
The newest version!
package matrix.boot.jdbc.config;
import lombok.extern.slf4j.Slf4j;
import matrix.boot.jdbc.beans.DynamicDataSource;
import matrix.boot.jdbc.beans.MoreDataSource;
import matrix.boot.jdbc.properties.JdbcProperties;
import matrix.boot.jdbc.scanner.DynamicDataSourceSwitchScanner;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* 动态数据源自动装配
* @author wangcheng
* 2021/8/16
**/
@EnableConfigurationProperties(JdbcProperties.class)
@ConditionalOnExpression("${matrix.jdbc.enabled} && '${matrix.jdbc.init-type}'.equals('Dynamic')")
@ImportAutoConfiguration(DynamicDataSourceSwitchScanner.class)
@Slf4j
public class DynamicDataSourceAutoConfiguration {
/**
* 动态数据源bean创建
*
* @param moreDataSource 多数据源信息
* @return 数据源
*/
@Bean
public DataSource dynamicDataSource(MoreDataSource moreDataSource) {
DynamicDataSource dynamicDataSource = new DynamicDataSource();
//获取主数据库
dynamicDataSource.setDefaultTargetDataSource(moreDataSource.getMasterDataSource());
//定义数据库列表
Map