package com.usoftchina.uas.office.jdbc;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.usoftchina.uas.office.context.ContextHolder;

/**
 * @author yingp
 * @date 2019/5/23
 */
public abstract class DataSourceHolder {

    private static final ThreadLocal<DataSourceBean> threadLocalBean = new TransmittableThreadLocal<>();

    /**
     * 获取当前数据源
     *
     * @return
     */
    public static DataSourceBean get() {
        return threadLocalBean.get();
    }

    /**
     * 切换到新数据源
     *
     * @param bean
     */
    public static void set(DataSourceBean bean) {
        threadLocalBean.set(bean);
        try {
            ContextHolder.getApplicationContext().getBean(DynamicDataSourceRegister.class).register(bean);
        } catch (Exception e) {
            throw new RuntimeException("错误数据连接", e);
        }
    }

    public static void clear() {
        threadLocalBean.set(null);
    }
}