001/**
002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (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 io.jboot.db.datasource;
017
018import io.jboot.utils.ConfigUtil;
019import io.jboot.utils.StrUtil;
020
021import java.util.HashMap;
022import java.util.Map;
023
024public class DataSourceConfigManager {
025
026    private static DataSourceConfigManager manager = new DataSourceConfigManager();
027
028    public static DataSourceConfigManager me() {
029        return manager;
030    }
031
032    private Map<String, DataSourceConfig> datasourceConfigs = new HashMap<>();
033
034    private DataSourceConfigManager() {
035        Map<String, DataSourceConfig> configMap = ConfigUtil.getConfigModels(DataSourceConfig.class, "jboot.datasource");
036        for (Map.Entry<String, DataSourceConfig> entry : configMap.entrySet()) {
037            DataSourceConfig config = entry.getValue();
038
039            //默认数据源
040            if ("default".equals(entry.getKey()) && StrUtil.isBlank(config.getName())) {
041                config.setName(DataSourceConfig.NAME_DEFAULT);
042            } else if (StrUtil.isBlank(config.getName())) {
043                config.setName(entry.getKey());
044            }
045
046            addConfig(config);
047        }
048    }
049
050    public void addConfig(DataSourceConfig config) {
051        if (config == null || !config.isConfigOk()) {
052            return;
053        }
054
055        datasourceConfigs.put(config.getName(), config);
056    }
057
058
059    public Map<String, DataSourceConfig> getDatasourceConfigs() {
060        return new HashMap<>(datasourceConfigs);
061    }
062
063    public DataSourceConfig getMainDatasourceConfig() {
064        return datasourceConfigs.get(DataSourceConfig.NAME_DEFAULT);
065    }
066}