Spring Boot 2.0 升級指南


Spring Boot 2.0 升級指南

前言

Spring Boot已經發布2.0有5個月多,多了很多新特性,一些坑也慢慢被填上,最近有空,就把項目中Spring Boot 版本做了升級,順便整理下升級的時候遇到的一些坑,做個記錄。后續的教程就以最新的2.03版本為主。參考官方文檔翻譯

在你開始之前

  • 2.x 至少需要 JDK 8 的支持,2.x 里面的許多方法應用了 JDK 8 的許多高級新特性,所以你要升級到 2.0 版本,先確認你的應用必須兼容 JDK 8。
    另外,2.x 開始了對 JDK 9 的支持。

  • 2.x 對第三方類庫升級了所有能升級的穩定版本,一些值得關注的類庫升級我給列出來了。

    1.Spring Framework 5+
    2.Tomcat 8.5+
    3.Flyway 5+
    4.Hibernate 5.2+
    5.Thymeleaf 3+

在 Spring Boot 2.0 中,許多配置屬性被重新命名/刪除,開發人員需要更新application.properties/ application.yml相應的配置。為了幫助你解決這一問題,Spring Boot 發布了一個新spring-boot-properties-migrator模塊。一旦作為該模塊作為依賴被添加到你的項目中,它不僅會分析應用程序的環境,而且還會在啟動時打印診斷信息,而且還會在運行時為您暫時遷移屬性。在您的應用程序遷移期間,這個模塊是必備的:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-properties-migrator</artifactId>
</dependency>

注意:遷移完成之后,請確保從項目的依賴關系中移除該模塊。

構建您的 Spring Boot 應用程序

Spring Boot Maven 插件
為了保持了一致性,並且避免與其他插件發生沖突,現在暴露的插件配置屬性都以一個spring-boot前綴開始。

例如,以下命令prod使用命令行啟用配置文件

mvn spring-boot:run -Dspring-boot.run.profiles=prod

Spring Boot 新特性,默認動態代理策略

Spring Boot現在默認使用CGLIB動態代理(基於類的動態代理), 包括AOP. 如果需要基於接口的動態代理(JDK基於接口的動態代理) , 需要設置spring.aop.proxy-target-class屬性為false.

開發 Web 應用程序嵌入式容器包裝結構

為了支持響應式用例,嵌入式容器包結構已經被大幅度的重構。 EmbeddedServletContainer已被重新命名為,WebServer並且該org.springframework.boot.context.embedded包已被重新定位到org.springframework.boot.web.embedded。例如,如果您使用TomcatEmbeddedServletContainerFactory回調接口定制嵌入式 Tomcat 容器,則應該使用TomcatServletWebServerFactory。

特定於 Servlet 的服務器屬性
許多server.* 屬性 ( Servlet 特有的) 已經轉移到server.servlet:

舊的屬性 新的屬性
server.context-parameters.* server.servlet.context-parameters.*
server.context-path server.servlet.context-path
server.jsp.class-name server.servlet.jsp.class-name
server.jsp.init-parameters.* server.servlet.jsp.init-parameters.*
server.jsp.registered server.servlet.jsp.registered
server.servlet-path server.servlet.path

模板引擎

Mustache模板默認的文件擴展名

Mustache模板的文件擴展名曾經是.html。現在的擴展名為.mustache,與官方規格和大多數的IDE插件保持一致。你可以通過更改spring.mustache.suffix配置文件的configuration key來重寫這個新的默認值。

Jackson/JSON支持

在2.0版本,我們已經設置Jackson配置文件的默認值,將ISO-8601 strings寫作了JSR-310。如果你希望返回之前的設置,可以添加spring.jackson.serialization.write-dates-as-timestamps=true 到你的配置文件中。

一個新的spring-boot-starter-json starter收集了必要的位去讀寫JSON。它不僅提供了jackson-databind,而且提供了和Java8一起運作的時候相當有用的組件:jackson-datatype-jdk8, jackson-datatype-jsr310 和jackson-module-parameter-names。如果你曾經手動地依賴這些組件,現在可以依賴這個新的starter取代。

HTTP/2 支持

為 Tomcat,Undertow 和 Jetty 提供 HTTP / 2 支持。支持取決於所選的 Web 服務器和應用程序環境(因為 JDK 8 不支持該協議)。

配置屬性的綁定

在 Spring Boot 2.0 中,用於綁定Environment屬性的機制@ConfigurationProperties已經完全徹底修改。我們借此機會收緊了松散綁定的規則,並修復了 Spring Boot 1.x 中的許多不一致之處。

新的BinderAPI 也可以@ConfigurationProperties直接在你自己的代碼之外使用。例如,下面將結合到List的CustomerProperty對象:

List<CustomerProperty> people = Binder.get(applicationContext.getEnvironment())
    .bind("customer.property", Bindable.listOf(CustomerProperty.class))
    .orElseThrow(IllegalStateException::new);

配置源可以像這樣在 YAML 中表示:

customer:
  property:
  - first-name: wang
    last-name: lao
  - first-name: li
    last-name: sheng

Actuator 改進

在 Spring Boot 2.0 中 Actuator endpoints 有很大的改進。所有 HTTP Actuator endpoints 現在都在該/actuator路徑下公開,並且生成的 JSON 有效負載得到了改進。

我們現在也不會在默認情況下暴露很多端點。如果您要升級現有的 Spring Boot 1.5 應用程序,請務必查看遷移指南並特別注意該management.endpoints.web.exposure.include屬性。

HikariCP

Spring Boot 2.0 中的默認數據庫池技術已從 Tomcat Pool 切換到 HikariCP。我們發現 Hakari 提供了卓越的性能,我們的許多用戶更喜歡 Tomcat Pool

初始化

數據庫初始化邏輯在 Spring Boot 2.0 中已經合理化。Spring Batch,Spring Integration,Spring Session 和 Quartz的初始化現在僅在使用嵌入式數據庫時才會默認發生。該enabled屬性已被替換為更具表現力枚舉。例如,如果你想一直執行 Spring Batch 的初始化,您可以設置spring.batch.initialize-schema=always。

如果 Flyway 或 Liquibase 正在管理您的 DataSource 的模式,並且您正在使用嵌入式數據庫,Spring Boot 現在會自動關閉 Hibernate 的自動 DDL 功能。

配置文件綁定

1.簡單類型
在Spring Boot 2.0中對配置屬性加載的時候會除了像1.x版本時候那樣移除特殊字符外,還會將配置均以全小寫的方式進行匹配和加載。所以,下面的4種配置方式都是等價的:

  • properties格式:
spring.jpa.databaseplatform=mysql
spring.jpa.database-platform=mysql
spring.jpa.databasePlatform=mysql
spring.JPA.database_platform=mysql
  • yaml格式:
spring:
  jpa:
    databaseplatform: mysql
    database-platform: mysql
    databasePlatform: mysql
    database_platform: mysql

Tips:推薦使用全小寫配合-分隔符的方式來配置,比如:spring.jpa.database-platform=mysql

2.List類型
在properties文件中使用[]來定位列表類型,比如:

spring.my-example.url[0]=http://example.com
spring.my-example.url[1]=http://spring.io

也支持使用逗號分割的配置方式,上面與下面的配置是等價的:

spring.my-example.url=http://example.com,http://spring.io

而在yaml文件中使用可以使用如下配置:

spring:
  my-example:
    url:
      - http://example.com
      - http://spring.io

也支持逗號分割的方式:

spring:
  my-example:
    url: http://example.com, http://spring.io

注意:在Spring Boot 2.0中對於List類型的配置必須是連續的,不然會拋出UnboundConfigurationPropertiesException異常,所以如下配置是不允許的:
name[0]=aaa
name[2]=bbb
在Spring Boot 1.x中上述配置是可以的,name[1]由於沒有配置,它的值會是null

3.Map類型
Map類型在properties和yaml中的標准配置方式如下:

properties格式:

spring.my-example.foo=bar
spring.my-example.hello=world

yaml格式:

spring:
  my-example:
    foo: bar
    hello: world

注意:如果Map類型的key包含非字母數字和-的字符,需要用[]括起來,比如:

spring:
  my-example:
    '[foo.baz]': bar

測試
對 Spring Boot 2.0 中提供的測試支持進行了一些補充和調整:

@WebFluxTest已添加新注釋以支持 WebFlux 應用程序的“切片”測試。
Converter和GenericConverter豆類現在自動掃描@WebMvcTest和@WebFluxTest。
@AutoConfigureWebTestClient已經添加了一個注釋來提供一個WebTestClientbean 供測試使用。注釋會自動應用於@WebFluxTest測試。
增加了一個新的ApplicationContextRunner測試實用程序,可以很容易地測試您的自動配置。我們已將大部分內部測試套件移至此新模型。詳細信息請參閱更新的文檔。

升級遇到的一些問題總結

1.Spring Data JPA 2.0.x findOne() 無效

在使用 Spring Data JPA 中,根據 主鍵獲得對象,一般是使用<S extends T> S findOne(Example<S> example); 方法,或者 T getOne(ID id);,在 spring-data-jpa 2.0.x版本中,獲取單個對象的方法改為 Optional<T> findById(ID id);返回的是一個Optional<T>(java8新特性)Optional 類是一個可以為null的容器對象。如果值存在則isPresent()方法會返回true,調用get()方法會返回該對象。delete()方法和findOne()類似也被去掉了,可以使用deleteById(Long id)來替換,還有一個不同點是deleteById(Long id)默認實現返回值為void。

spring-data-jpa 1.5.2 的CrudRepository 接口

@NoRepositoryBean
public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {

    <S extends T> S save(S entity);

    <S extends T> Iterable<S> save(Iterable<S> entities);

    T findOne(ID id);

    boolean exists(ID id);

    Iterable<T> findAll();

    Iterable<T> findAll(Iterable<ID> ids);

    long count();

    void delete(ID id);

    void delete(T entity);

    void delete(Iterable<? extends T> entities);

    void deleteAll();
}

spring-data-jpa 2.0.8 的CrudRepository 接口

@NoRepositoryBean
public interface CrudRepository<T, ID> extends Repository<T, ID> {

    <S extends T> S save(S entity);

    <S extends T> Iterable<S> saveAll(Iterable<S> entities);

    Optional<T> findById(ID id);

    boolean existsById(ID id);

    Iterable<T> findAll();

    Iterable<T> findAllById(Iterable<ID> ids);

    long count();

    void deleteById(ID id);

    void delete(T entity);

    void deleteAll(Iterable<? extends T> entities);

    void deleteAll();
}

2.@GeneratedValue(strategy = GenerationType.AUTO)Spring Boot 2.0 需要指定主鍵的自增策略,這個和 Spring Boot 1.0 有所區別,1.0 會使用默認的策略@GeneratedValue(strategy = GenerationType.IDENTITY)

@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private long id;

3.jpa2.0的方言設置如果需要指定InnoDB存儲引擎可以使用database-platform: org.hibernate.dialect.MySQL57InnoDBDialect默認會使用myisam(不支持事務)在jpa中無法體現換成mybatis可以很好的驗證。

4.日志類報錯:Spring Boot 2.0 默認不包含 log4j,建議使用 slf4j 。

import org.apache.log4j.Logger;
protected Logger logger = Logger.getLogger(this.getClass());

改為:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
protected Logger logger =  LoggerFactory.getLogger(this.getClass());

5.Thymeleaf 3.0 默認不包含布局模塊。

將 Pom 包升級到 2.0之后,訪問首頁的時候一片空白什么都沒有,查看后台也沒有任何的報錯信息,首先嘗試着跟蹤了 http 請求,對比了一下也沒有發現什么異常,在查詢 Thymeleaf 3.0 變化時才發現:Spring Boot 2.0 中spring-boot-starter-thymeleaf 包默認並不包含布局模塊,需要使用的時候單獨添加,添加布局模塊如下:

<dependency>
   <groupId>nz.net.ultraq.thymeleaf</groupId>
   <artifactId>thymeleaf-layout-dialect</artifactId>
</dependency>

6.分頁組件PageRequest變化。

在 Spring Boot 2.0 中 ,方法new PageRequest(page, size, sort) 已經過期不再推薦使用,推薦使用以下方式來構建分頁信息:
Pageable pageable =PageRequest.of(page, size, Sort.by(Sort.Direction.ASC,"id"));
跟蹤了一下源碼發現PageRequest.of()方法,內部還是使用的new PageRequest(page, size, sort),只是最新的寫法更簡潔一些。

public static PageRequest of(int page, int size, Sort sort) {
    return new PageRequest(page, size, sort);
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM