在應用程序啓動後,能夠自動執行建庫、建表等SQL腳本.下文中以要自動化執行people.sql腳本爲例說明,腳本在SpringBoot工程中的路徑爲:classpath:people.sql,腳本的具體內容以下:html
CREATE TABLE IF NOT EXISTS people( persion_id BIGINT NOT NULL AUTO_INCREMENT, first_name VARCHAR(20), last_name VARCHAR(20), PRIMARY KEY (persion_id) );
在SpringBoot的架構中,DataSourceInitializer類能夠實現自動執行腳本的功能。經過自定義DataSourceInitializer Bean就能夠實現按照業務要求執行特定的腳本。java
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; @Configuration public class BatchTaskDataSourceInitializer { /** * 構建Resource對象 */ @Value("classpath:schema-all.sql") private Resource businessScript; /** * 自定義Bean實現業務的特殊需求 * @param dataSource * @return */ @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(businessScript); return populator; } }