package com.op.common.datasource.creator;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * 动态创建数据源
 *
 * @ClassName: DynamicDatasourceCreator
 * @Description: TODO
 * @author shichangzhou
 * @date 2023年4月20日 下午1:15:09
 */
@Component
public class DynamicDatasourceCreator {

	private static final Logger log = LoggerFactory.getLogger(DynamicDatasourceCreator.class);
	@Resource
	private DynamicRoutingDataSource dynamicRoutingDataSource;
	@Resource
	private DefaultDataSourceCreator defaultDataSourceCreator;

	public DataSource createDynamicDataSource(DataSourceProperty dataSourceProperty) {
		log.info("Dynamic Datasource init.....");
		DataSource dataSource = defaultDataSourceCreator.createDataSource(dataSourceProperty);
		dynamicRoutingDataSource.addDataSource(dataSourceProperty.getPoolName(), dataSource);
		return dataSource;
	}
}
