2

1.xml配置数据库连接配置

#数据源配置
spring.datasource.username=beebotlark
spring.datasource.password=WDShxRWTLSuKM6ucPN4E8hi0YWglium26wJVKitxRpzN2sopztgZpvgi4YFnuPXrAiLPMjuzgYK13we5SEwIHQ==spring.datasource.url=localhost:3306/local?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.is-init=false
spring.datasource.init_file_name=DML,DDL
#公钥
spring.datasource.public-key=MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAN/HfAEsiZ/uXs3/wKTa6BSUr/6QF/sAcHIoHMO56TFiNDPXpnwtsUC5JJDu1rq9kxU0Ilc0CVEYZ5g5aD23ZVkCAwEAAQ==
#配置解密
spring.datasource.druid.filters=config
spring.datasource.druid.connection-properties=config.decrypt=true;config.decrypt.key=${spring.datasource.public-key}

2.创建DruidConfig配置类

@Configuration
public class DruidConfig{

}

3.注入配置文件中的数据库配置

 /**
     * datasourceUrl 连接数据库url
     */
    @Value("${spring.datasource.url}")
    private String datasourceUrl;

    /**
     * driverClassName 数据库驱动
     */
    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;
    /**
     * datasourceUserName 连接数据库的用户名
     */
    @Value("${spring.datasource.username}")
    private String datasourceUserName;

    /**
     * databasePassword 连接数据库密码
     */
    @Value("${spring.datasource.password}")
    private String databasePassword;

    /**
     * 注入数据库公钥
     */
    @Value("${spring.datasource.public-key}")
    private String datasourcePublicKey;

4.调用druid公钥+密码钥进行解密,并执行创建数据库语句

/**
     * @return dataSource
     * @description 配置数据库自动创建
     * 如果连接地址没有对应的数据库则创建,前提是有root账号,或者是非root账号具有建库的权限
     */
    @Bean
    public DataSource dataSourceConfig() {
        DruidDataSource dataSource = new DruidDataSource();
        String decrypt = null;
        //druid解密
        try {
            decrypt = ConfigTools.decrypt(datasourcePublicKey, databasePassword);
        } catch (Exception e) {
            log.error("公钥解密异常:{}", e.getMessage());
        }
        dataSource.setUrl(datasourceUrl);
        dataSource.setUsername(datasourceUserName);
        //将解密后的密码添加到datasource源
        dataSource.setPassword(decrypt);
        dataSource.setDriverClassName(driverClassName);
        Connection connection = null;
        PreparedStatement state = null;
        try {
            Class.forName(driverClassName);
            // 截取数据库问问好前的连接参数
            String sqlUrl = datasourceUrl.substring(0, datasourceUrl.indexOf("?"));
            // 获取连接数据库的url
            String databasesUrl = sqlUrl.substring(0, sqlUrl.lastIndexOf("/"));
            // 截取数据库名
            String databaseName = sqlUrl.substring(sqlUrl.lastIndexOf("/") + 1);
            // 创建连接
            connection = DriverManager.getConnection(databasesUrl, datasourceUserName, decrypt);
            // 创建传输通道,并设置占位符
            String sql = "create database if not exists ? default character set utf8 COLLATE utf8_general_ci";
            state = connection.prepareStatement(sql);
            // 将数据库名注入到占位符
            state.setString(1, databaseName);
            // 获取到注入的sql语句
            String resultSql = ((ClientPreparedStatement) state).asSql();
            String executeSql = resultSql.replaceAll("'", "`");
            int execute = state.executeUpdate(executeSql);
            log.info("sql语句执行状态:{}", execute);
        } catch (Throwable e) {
            log.error("数据库连接异常:{}", e.getMessage());
        } finally {
            try {
                if (null != state) {
                    state.close();
                }
                if (null != connection) {
                    connection.close();
                }
            } catch (SQLException throwable) {
                log.error("sql语句异常:{}", throwable.getMessage());
            }
        }
        return dataSource;
    }

Zeran
32 声望4 粉丝

学而不思则罔,思而不学则殆。