Spring Boot项目——项目启动自动执行sql脚本
背景
- 在项目上线前,需要提供一批测试数据到数据库,数据需求是:每次修改缺陷重启项目后,测试数据会初始化成最初的数据
核心思想
- 在SpringBoot的架构中,DataSourceInitializer类可以在项目启动后初始化数据,我们可以通过自动执行自定义sql脚本初始化数据。通过自定义DataSourceInitializer Bean就可以实现按照业务要求执行特定的脚本。
使用
- 前提:项目数据源配置完成
- 方法
- 通过@Configuration、@Bean和@Value三个注解实现自定义DataSourceInitializer Bean,现在Bean的定义中实现自动化执行脚本的业务逻辑。
- 代码如下
package com.test.integration.rpc.initdata; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; import org.springframework.jdbc.datasource.init.DataSourceInitializer; import org.springframework.jdbc.datasource.init.DatabasePopulator; import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; import javax.sql.DataSource; /** * @author test * @Description: 自定义初始化数据源 * @date 2020/4/11 */ @Configuration public class CustomizeDataSourceInitializer { @Value("classpath:testSql/test_farms.sql") private Resource functionScriptFarms; @Value("classpath:testSql/test_miners.sql") private Resource functionScriptMiners; @Value("classpath:testSql/test_pool_config.sql") private Resource functionScriptPoolConfig; @Bean public DataSourceInitializer dataSourceInitializer(final DataSource dataSource) { final DataSourceInitializer initializer = new DataSourceInitializer(); // 设置数据源 initializer.setDataSource(dataSource); initializer.setDatabasePopulator(databasePopulator()); return initializer; } private DatabasePopulator databasePopulator() { final ResourceDatabasePopulator populator = new ResourceDatabasePopulator(); populator.addScripts(functionScriptFarms); populator.addScripts(functionScriptMiners); populator.addScripts(functionScriptPoolConfig); return populator; } }
-
- SQL脚本如下:例子test_pool_config.sql
delete from `pool_configs`; INSERT INTO `pool_configs`(`pool_config_id`, `cdate`, `mdate`, `pool_config_mid` ) VALUES (1, '2020-04-10 18:02:54', '2020-04-10 18:02:54', 'bcf2a18a-b38b-4e3a-8852-7efbabc7954d'); INSERT INTO `pool_configs`(`pool_config_id`, `cdate`, `mdate`, `pool_config_mid` ) VALUES (2, '2020-04-10 18:02:54', '2020-04-10 18:02:54', 'bcf3a18a-b38b-4e3a-8852-7efbabc7954d'); INSERT INTO `pool_configs`(`pool_config_id`, `cdate`, `mdate`, `pool_config_mid` ) VALUES (3, '2020-04-10 18:02:54', '2020-04-10 18:02:54', 'bcf4a18a-b38b-4e3a-8852-7efbabc7954d'); INSERT INTO `pool_configs`(`pool_config_id`, `cdate`, `mdate`, `pool_config_mid` ) VALUES (4, '2020-04-10 18:02:54', '2020-04-10 18:02:54', 'bcf5a18a-b38b-4e3a-8852-7efbabc7954d');