1.在项目的resources下创建sql文件
2. 配置application.yml或者application.properties
3. sql初始化执行类
import lombok.extern.slf4j.Slf4j; 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 hdx * @version 1.0.0 * @ClassName
BatchTaskDataSourceInitializer.java * @Description 执行sql文件 * @createTime
2022年05月16日 09:28:00 */ @Slf4j @Configuration public class
BatchDataSourceInitializer { /** * 构建Resource对象 */
@Value("${spring.sql.createsql}") private Resource createsql; /** *
自定义Bean实现业务的特殊需求 * @param dataSource * @return */ @Bean public
DataSourceInitializer dataSourceInitializer(final DataSource dataSource) { try
{ final DataSourceInitializer initializer = new DataSourceInitializer(); //
设置数据源 initializer.setDataSource(dataSource);
initializer.setDatabasePopulator(databasePopulator()); log.info("sql文件执行成功");
return initializer; } catch (Exception e) { log.info("sql文件执行失败:", e); } return
null; } private DatabasePopulator databasePopulator() { final
ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
populator.addScripts(createsql); return populator; } }
4.启动测试
执行成功,去数据库看下表结构。
如果运行不行成功,请留言咨询