Spring Boot 2.5.0 從新設計的spring.sql.init 配置有啥用?

前幾天Spring Boot 2.5.0發佈了,其中提到了關於Datasource初始化機制的調整,有讀者私信想了解這方面作了什麼調整。那麼今天就要詳細說說這個從新設計的配置內容,並結合實際狀況說說個人理解和實踐建議。java

棄用內容

先來糾正一個誤區。主要以前在版本更新介紹的時候,存在一些表述上的問題。致使部分讀者認爲此次的更新是Datasource自己初始化的調整,但其實並非。此次從新設計的只是對Datasource腳本初始化機制的從新設計。mysql

先來看看此次被棄用部分的內容(位於org.springframework.boot.autoconfigure.jdbc.DataSourceProperties),若是你有用過這些配置內容,那麼新配置就很容易理解了。git

/**
     * Mode to apply when determining if DataSource initialization should be performed
     * using the available DDL and DML scripts.
     */
    @Deprecated
    private DataSourceInitializationMode initializationMode = DataSourceInitializationMode.EMBEDDED;

    /**
     * Platform to use in the DDL or DML scripts (such as schema-${platform}.sql or
     * data-${platform}.sql).
     */
    @Deprecated
    private String platform = "all";

    /**
     * Schema (DDL) script resource references.
     */
    private List<String> schema;

    /**
     * Username of the database to execute DDL scripts (if different).
     */
    @Deprecated
    private String schemaUsername;

    /**
     * Password of the database to execute DDL scripts (if different).
     */
    @Deprecated
    private String schemaPassword;

    /**
     * Data (DML) script resource references.
     */
    @Deprecated
    private List<String> data;

    /**
     * Username of the database to execute DML scripts (if different).
     */
    @Deprecated
    private String dataUsername;

    /**
     * Password of the database to execute DML scripts (if different).
     */
    @Deprecated
    private String dataPassword;

    /**
     * Whether to stop if an error occurs while initializing the database.
     */
    @Deprecated
    private boolean continueOnError = false;

    /**
     * Statement separator in SQL initialization scripts.
     */
    @Deprecated
    private String separator = ";";

    /**
     * SQL scripts encoding.
     */
    @Deprecated
    private Charset sqlScriptEncoding;

對應到配置文件裏的屬性以下(這裏僅列出部分,就不所有列出了,主要就是對應上面源碼中的屬性):github

spring.datasource.schema=
spring.datasource.schema-username=
spring.datasource.schema-password=
...

這些配置主要用來指定數據源初始化以後要用什麼用戶、去執行哪些腳本、遇到錯誤是否繼續等功能。spring

新的設計

Spring Boot 2.5.0開始,啓用了全新的配置方式,咱們能夠從這個類org.springframework.boot.autoconfigure.sql.init.SqlInitializationProperties裏看到詳情。sql

下面咱們經過一個簡單的例子來體驗這個功能的做用。數據庫

  • 建立一個Spring Boot的基礎應用,並在pom.xml中引入和mysql的依賴:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
  • 在配置文件中增長數據源和初始化數據源的配置,具體以下:
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# Spring Boot 2.5.0 init schema & data
# 執行初始化腳本的用戶名稱
spring.sql.init.username=root
# 執行初始化腳本的用戶密碼
spring.sql.init.password=
# 初始化的schema腳本位置
spring.sql.init.schema-locations=classpath*:schema-all.sql
  • 根據上面配置的定義,接下來就在resource目錄下,建立腳本文件schema-all.sql,並寫入一些初始化表結構的腳本
create table test.user_info
(
    id          int unsigned auto_increment comment '用戶id'
        primary key,
    open_id     varchar(255)     default '' null comment '微信小程序openid',
    nick_name   varchar(255)     default '' null comment '微信名',
    head_img    varchar(255)     default '' null comment '微信頭像',
    sex         varchar(255)     default '' null comment '性別',
    phone       varchar(255)     default '' null comment '手機',
    province    varchar(255)     default '' null comment '註冊地址:省',
    city        varchar(255)     default '' null comment '註冊地址:城市',
    country     varchar(255)     default '' null comment '註冊地址:縣/區',
    status      tinyint unsigned default 0  not null comment '是否標記刪除 0:否 1:是',
    create_time datetime                    not null comment '建立時間',
    update_time datetime                    not null comment '更新時間'
)
comment '用戶表';
  • 完成上面步驟以後,啓動應用。而後打開MySQL客戶端,能夠看到在test庫下,多了一個user_info

經過上面的例子,不難想到這樣的功能主要能夠用來管理應用啓動與數據庫配置的自動執行,以減小應用部署過程當中手工執行的內容,下降應用部署的執行步驟。小程序

配置詳解

除了上面用到的配置屬性以外,還有一些其餘的配置,下面詳細講解一下做用。微信小程序

  • spring.sql.init.enabled:是否啓動初始化的開關,默認是true。若是不想執行初始化腳本,設置爲false便可。經過-D的命令行參數會更容易控制。
  • spring.sql.init.usernamespring.sql.init.password:配置執行初始化腳本的用戶名與密碼。這個很是有必要,由於安全管理要求,一般給業務應用分配的用戶對一些建表刪表等命令沒有權限。這樣就能夠與datasource中的用戶分開管理。
  • spring.sql.init.schema-locations:配置與schema變動相關的sql腳本,可配置多個(默認用;分割)
  • spring.sql.init.data-locations:用來配置與數據相關的sql腳本,可配置多個(默認用;分割)
  • spring.sql.init.encoding:配置腳本文件的編碼
  • spring.sql.init.separator:配置多個sql文件的分隔符,默認是;
  • spring.sql.init.continue-on-error:若是執行腳本過程當中碰到錯誤是否繼續,默認是false`;因此,上面的例子第二次執行的時候會報錯並啓動失敗,由於第一次執行的時候表已經存在。

應用建議

關於這些配置的應用,相信聰明的你必定會把它與數據庫的版本管理聯繫起來(由於能夠自動的執行腳本)。安全

那麼依靠這些配置,是否能夠勝任業務應用部署時候數據庫初始化的自動化實現呢?

我的認爲就上述所介紹的配置,雖然具有了必定的自動執行能力。但因爲缺失對當前環境的判斷能力,因此要應對實際的部署場景來講,仍是遠遠不夠的。

若是要自動化的管理數據庫表結構、初始化數據的話,個人建議是:

  1. 默認提供的這個初始化功能能夠且僅用於單元測試,自動建立數據庫結構與初始化數據,使用完畢後銷燬。能夠方便的控制每次單元測試的執行環境一致。
  2. 應用在環境部署的時候,仍是要使用以前介紹過的Flyway來實現,如何使用可見以前的分享:使用Flyway來管理數據庫版本
  3. 聯合Flyway一同使用,經過org.springframework.jdbc.datasource.init.DataSourceInitializer來定義更復雜的執行邏輯。

更多本系列免費教程連載「點擊進入彙總目錄」

代碼示例

本文的相關例子能夠查看下面倉庫中的chapter3-13目錄:

原創不易,若是您以爲本文不錯,歡迎Star支持,您的關注是我堅持的動力!

歡迎關注個人公衆號:程序猿DD,分享其餘地方看不到的知識與思考
相關文章
相關標籤/搜索