package com.hqhp.salesys.common.config;
import cn.hutool.core.io.file.FileReader;
import com.baomidou.dynamic.datasource.provider.AbstractDataSourceProvider;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import com.hqhp.salesys.common.constant.HqhpConstant;
import com.hqhp.salesys.common.properties.HqhpProperties;
import com.hqhp.salesys.common.utils.DesDelphi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.io.File;
import java.util.Map;
/**
* @author xucj
* @date 2022/08/11/16:37
*
* 自定义yml文件动态数据源解析类
* 处理数据库密码从指定文件获取密码字段并解密设置到上下文中
*/
@Component
public class MyYmlDynamicDataSourceProvider extends AbstractDataSourceProvider implements DynamicDataSourceProvider {
@Autowired
private HqhpProperties hqhpProperties;
private DynamicDataSourceProperties properties;
public MyYmlDynamicDataSourceProvider(DynamicDataSourceProperties properties) {
this.properties = properties;
}
@Override
public Map loadDataSources() {
Map dataSourcePropertiesMap = this.properties.getDatasource();
DataSourceProperty dataSourceProperty = dataSourcePropertiesMap.get(HqhpConstant.MASTER);
if(dataSourceProperty != null){
File file = new File(hqhpProperties.getCretPath() + HqhpConstant.DB_FILE);
if(file.isFile()){
FileReader fileReader = FileReader.create(file);
dataSourceProperty.setPassword(DesDelphi.decrypt(fileReader.readString(), HqhpConstant.DB_SECRET_KEY));
}
}
return this.createDataSourceMap(dataSourcePropertiesMap);
}
}