Mybatis-plus 动态添加/删除数据源

mybatis-plus version : 3.4.3.1

spring-boot version : 2.3.5.RELEASE


@Service
public class DynamaicRoutingDataSourceManagerImpl implements IDynamaicRoutingDataSourceManager {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private DataSourceCreator dataSourceCreator;


    @Override
    public DataSource now(String key) {
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        return ds.getCurrentDataSources().get(key);
    }

    @Override
    public void add(DataSourceProperty dataSourceProperty) {
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);
        ds.addDataSource(dataSourceProperty.getPoolName(), dataSource);
    }

    @Override
    public void remove(String key) {
        if (now(key) == null) {
            return;
        }
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        ds.removeDataSource(key);
    }
}

///如果此时也没有 Entity,使用原生的 JdbcTemplate ,则需要考虑多例模式。

@Scope("prototype")

//这里要考虑多例模式的,并不是 DynamaicRoutingDataSourceManagerImpl

你可能感兴趣的:(java,spring,spring,java,后端,mybatis-plus,动态数据源)