Spring实现动态数据源

2021-04-05  本文已影响0人  知止9528

BeanDefinition注册

/**
 * 数据源Spring Bean注册
 *
 */
@Slf4j
@Component
public class DataSourceBeanDefinitionRegistry implements BeanFactoryAware {

    /**
     *  data source mapper
     */
    @Autowired
    private DataSourceMapper dataSourceMapper;

    /**
     * bean factory
     */
    private DefaultListableBeanFactory beanFactory;

    @PostConstruct
    public void initDataSource() {

        log.info("============================init indicator data source============================");

        // 查询所有数据源
        List<IndicatorDataSourceEntity> dataSourceList = dataSourceMapper.select();
        if (CollectionUtils.isEmpty(dataSourceList)) {
            log.error("the data source of indicator card is error");
            throw new BaseException(BaseExceptionMessage.SYSTEM_ERROR);
        }

        // 去重
        Map<String, IndicatorDataSourceEntity> dataSourceMap = dataSourceList.stream()
                .collect(Collectors.toMap(IndicatorDataSourceEntity::getDataInstance, object -> object, (a, b) -> a));

        dataSourceMap.values().forEach(dataSource -> {
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(DataSource.class);
            GenericBeanDefinition beanDefinition = (GenericBeanDefinition) builder.getRawBeanDefinition();
            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(dataSource.getConnectionProperties());
            beanDefinition.setBeanClass(JdbcTemplateFactoryBean.class);
            beanDefinition.setAutowireMode(GenericBeanDefinition.AUTOWIRE_BY_TYPE);
            beanDefinition.setLazyInit(true);
            beanFactory.registerBeanDefinition(dataSource.getDataInstance(), beanDefinition);

            log.info("{} data source initialized successfully", dataSource.getDataInstance());
        });

        log.info("============================init indicator data source============================");
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        this.beanFactory = (DefaultListableBeanFactory) beanFactory;
    }
}

jdbcTemplate

/**
 * the factory bean of jdbc template
 */
@Slf4j
public class JdbcTemplateFactoryBean implements FactoryBean<JdbcTemplate> {

    /**
     * cyberark object
     */
    private static final String DRUID_DB_OBJECT = "druid.db.object";

    /**
     * druid password
     */
    private static final String DRUID_PASS = "druid.password";

    /**
     * cyberark password helper
     */
    @Autowired
    private PasswordHelper passwordHelper;

    /**
     * 数据源配置
     */
    private String dataSourceConfig;

    public JdbcTemplateFactoryBean(String dataSourceConfig) {
        this.dataSourceConfig = dataSourceConfig;
    }

    @Override
    public JdbcTemplate getObject()  {
        Properties properties = MapUtils.toProperties(JSONObject.parseObject(this.dataSourceConfig));
        if (StringUtils.isNotBlank(properties.getProperty(DRUID_DB_OBJECT))) {
            properties.setProperty(DRUID_PASS, passwordHelper.getPassword(properties.getProperty(DRUID_DB_OBJECT)));
        }
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.configFromPropety(properties);
        return new JdbcTemplate(druidDataSource);
    }

    @Override
    public Class<?> getObjectType() {
        return JdbcTemplate.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读