package com.qmth.boot.mybatis.config;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * 数据源自动配置
 */
@Configuration
@AutoConfigureBefore(org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration.class)
@ComponentScan("com.qmth.boot.mybatis")
public class DataSourceAutoConfiguration {

    @Bean
    public DataSource dataSource(DataSourceProperties dataSourceProperties) {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName(dataSourceProperties.getDriverClassName());
        dataSource.setJdbcUrl(dataSourceProperties.getUrl());
        dataSource.setUsername(dataSourceProperties.getUsername());
        dataSource.setPassword(dataSourceProperties.getPassword());
        dataSource.setMinimumIdle(dataSourceProperties.getMinIdle());
        dataSource.setMaximumPoolSize(dataSourceProperties.getMaxPoolSize());
        dataSource.setMaxLifetime(dataSourceProperties.getMaxLifetime().toMillis());
        dataSource.setIdleTimeout(dataSourceProperties.getIdleTimeout().toMillis());
        dataSource.setConnectionTimeout(dataSourceProperties.getConnectionTimeout().toMillis());
        return dataSource;
    }

}
