Spring Boot 2.0 遷移指南(1.5升級2.0版本特性變化)

Spring Boot 2.0 遷移指南

此文根據(jù)springboot在GitHub上的Spring Boot 2.0 遷移指南文章篮赢,做出中文解釋使其通俗易懂齿椅,旨在為自己以及各位了解spring、springboot更多的特性與使用方法启泣。
注意涣脚,這不是翻譯。

Before You Start

Upgrade to the latest 1.5.x version

Before you start the upgrade, make sure to upgrade to the latest 1.5.x available version. This will make sure that you are building against the most recent dependencies of that line.

官方建議我們先升級到1.5.X版本寥茫,運(yùn)行成功后遣蚀,再升級2.0,減小升級版本的差異纱耻,提升穩(wěn)定性芭梯。

Review dependencies

The move to Spring Boot 2 will upgrade a number of dependencies and might require work on your end. You can review dependency management for 1.5.x with dependency management for 2.0.x to asses how your project is affected.
You may also use dependencies that are not managed by Spring Boot (e.g. Spring Cloud). As your project defines an explicit version for those, you need first to identify the compatible version before upgrading.

大版本升級,很多組件依賴也會(huì)隨之升級弄喘,需要評估好這些組件間接升級的影響玖喘。不過也可以自己引入其他包含自己指定版本組件的依賴,把springboot2.0里的排除掉蘑志。

Review custom configuration

Any user-configuration that your project defines might need to be reviewed on upgrade. If this can be replaced by use of standard auto-configuration, do it so before upgrading.

檢查自定義的Config配置會(huì)不會(huì)受影響累奈,如果可以使用springboot的自動(dòng)配置能力,就別自定義了急但,浪費(fèi)時(shí)間還增加springboot版本升級成本澎媒。

Review system requirements

Spring Boot 2.0 requires Java 8 or later. Java 6 and 7 are no longer supported. It also requires Spring Framework 5.0.

springboot2.0開始只支持java8及以后版本,spring依賴升級到5.0波桩。

Upgrade to Spring Boot 2

Once you have reviewed the state of your project and its dependencies, upgrade to the latest maintenance release of Spring Boot 2.0. In particular, do not upgrade to Spring Boot 2.0.0.RELEASE as a number of issues have been reported and fixed.
We also recommend to upgrade in phases and not in one jump to the latest GA: first upgrade to 2.0, then 2.1, etc.

做完升級前的檢查后戒努,就可以正式升級了,不過不建議升級到2.0.0.RELEASE镐躲,一般來說储玫,2.x表示新特性增加,2.0.x表示各類問題修復(fù)萤皂,不會(huì)引入新特性撒穷。所以,可以直接升級到比如2.0.9.RELEASE敌蚜,2.0x最新的版本。
然后窝爪,再逐步升級到2.1.x弛车、2.2.x等等。

Configuration properties migration

With Spring Boot 2.0, many configuration properties were renamed/removed and developers need to update their application.properties/application.yml accordingly. To help you with that, Spring Boot ships a new spring-boot-properties-migrator module. Once added as a dependency to your project, this will not only analyze your application’s environment and print diagnostics at startup, but also temporarily migrate properties at runtime for you. This is a must have during your application migration:
Note:Once you’re done with the migration, please make sure to remove this module from your project’s dependencies.

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

升級后會(huì)有很多配置屬性字段過期或刪除蒲每,可以引入這個(gè)依賴纷跛,啟動(dòng)項(xiàng)目后,它會(huì)輸出可替換的新的配置屬性字段邀杏。

Building Your Spring Boot Application

Spring Boot Maven plugin

The plugin configuration attributes that are exposed as properties now all start with a spring-boot prefix for consistency and to avoid clashes with other plugins.
For instance, the following command enables the prod profile using the command line:
mvn spring-boot:run -Dspring-boot.run.profiles=prod

一些命令行發(fā)生了變化贫奠,比如1.x里:

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

2.x里唬血,加上了spring-boot前綴:

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

Custom include/exclude patterns have been aligned to latest Surefire’s defaults. If you were relying on ours, update your plugin configuration accordingly. They used to be as follows:
Tip:If you are using JUnit 5, you should upgrade Surefire to 2.22.0.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
        <includes>
             <include>**/*Tests.java</include>
             <include>**/*Test.java</include>
        </includes>
        <excludes>
            <exclude>**/Abstract*.java</exclude>
        </excludes>
    </configuration>
</plugin>

沒看懂啥意思,平時(shí)也不怎么用這個(gè)插件唤崭。反正就是用JUnit 5拷恨,surefire 要升級到 2.22.0。

Spring Boot Gradle Plugin

Spring Boot’s Gradle plugin has been largely rewritten to enable a number of significant improvements. You can read more about the plugin’s capabilities in its reference and api documentation.

springboot的gradle插件進(jìn)行了重寫改進(jìn)谢肾。

Dependency Management

Spring Boot’s Gradle plugin no longer automatically applies the dependency management plugin. Instead, Spring Boot’s plugin now reacts to the dependency management plugin being applied by importing the correct version of the spring-boot-dependencies BOM. This gives you more control over how and when dependency management is configured.
For most applications applying the dependency management plugin will be sufficient:
Note:The dependency management plugin remains a transitive dependency of spring-boot-gradle-plugin so there’s no need for it to be listed as a classpath dependency in your buildscript configuration.

apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management' // <-- add this to your build.gradle

沒用過gradle腕侄,意思應(yīng)該是 io.spring.dependency-management 插件需要手動(dòng)添加,而不是自動(dòng)引入了芦疏。

Building Executable Jars and Wars

The bootRepackage task has been replaced with bootJar and bootWar tasks for building executable jars and wars respectively. The jar and war tasks are no longer involved.

老的springboot用gradle打包方式參考https://www.kancloud.cn/george96/java-springboot/613950
2.0里的打包方式參考
Spring Boot Gradle Plugin Reference Guide
即bootRepackage 被替換成了bootJar和bootWar 冕杠。

Configuration Updates

The BootRun, BootJar, and BootWar tasks now all use mainClassName as the property to configure the name of the main class. This makes the three Boot-specific tasks consistent with each other, and also aligns them with Gradle’s own application plugin.

mainClassName即啟動(dòng)類 xxxApplication,現(xiàn)在可以作為屬性進(jìn)行配置酸茴。

Spring Boot Features

Default Proxying Strategy

Spring Boot now uses CGLIB proxying by default, including for the AOP support. If you need interface-based proxy, you’ll need to set the spring.aop.proxy-target-class to false.

springboot2.0默認(rèn)使用cglib作為動(dòng)態(tài)代理模式分预,即使類實(shí)現(xiàn)了接口,可以通過配置屬性spring.aop.proxy-target-class=false將默認(rèn)代理切換為jdk薪捍。不過spring5.0其實(shí)還是默認(rèn)jdk代理的笼痹。

SpringApplication

Web Environment

Spring Boot applications can now operate in more modes so spring.main.web-environment property is now deprecated in favor of spring.main.web-application-type that provides more control.
If you want to make sure an application doesn’t start a web server you’d have to change the property to:
Tip: there is also a setWebApplicationType on SpringApplication if you want to do that programmatically.

spring.main.web-application-type=none

為了適應(yīng)響應(yīng)式編程的新潮流,增加了REACTIVE模式飘诗。除了配置屬性与倡,也可以編程式實(shí)現(xiàn):

    public static void main(String[] args) {
        SpringApplication springApplication = new SpringApplication(Application.class);
        springApplication.setWebApplicationType(WebApplicationType.NONE);
        springApplication.run(args);
    }
Spring Boot Application Events Changes

We’ve added a new event, ApplicationStartedEvent. ApplicationStartedEvent is sent after the context has been refreshed but before any application and command-line runners have been called. ApplicationReadyEvent is sent after any application and command-line runners have been called. It indicates that the application is ready to service requests.
See the updated reference documentation.

新增了ApplicationStartingEvent,ApplicationXXXEvent中引入了context上下文昆稿。這屬于SpringApplicationRunListener 應(yīng)用監(jiān)聽器功能相關(guān)的改進(jìn)纺座,具體應(yīng)用可以看EventPublishingRunListener類設(shè)計(jì)介紹

Banner

In our effort to limit the number of root namespaces that Spring Boot uses, banner-related properties have been relocated to spring.banner.

這是日志、控制臺(tái)打印的文字圖片banner溉潭,屬性名稱增加了spring前綴净响,順便百度看到個(gè)動(dòng)態(tài)banner

Externalized Configuration

Relaxed Binding

The rules related to relaxed binding have been tightened
This new relaxed bindings as several advantages:
1.There is no need to worry about the structure of the key in @ConditionalOnProperty: you must now use the canonical format (acme.my-property and not acme.myProperty), the supported relaxed variants will work transparently. If you were using the prefix attribute you can now simply put the full key using the name or value attributes.
2.RelaxedPropertyResolver is no longer available as the Environment takes care of that automatically: env.getProperty("com.foo.my-bar") will find a com.foo.myBar property.
The org.springframework.boot.bind package is no longer available and is replaced by the new relaxed binding infrastructure. In particular, RelaxedDataBinder and friends have been replaced with a new Binder API. The following samples binds MyProperties from the app.acme prefix.

MyProperties target = Binder.get(environment)
        .bind("app.acme", MyProperties.class)
        .orElse(null);

As relaxed binding is now built-in, you can request any property without having to care about the case as long as it’s using one of the supported formats:

FlagType flagType = Binder.get(environment)
        .bind("acme.app.my-flag", FlagType.class)
        .orElse(FlagType.DEFAULT);

1.@ConditionalOnProperty注解匹配屬性名稱的規(guī)則更加嚴(yán)格喳瓣,不再支持駝峰轉(zhuǎn)換(我試了下馋贤,- 和_ 可以互轉(zhuǎn),離譜)畏陕,建議配置屬性長啥樣配乓,匹配名稱就怎么寫好了。
2.RelaxedPropertyResolver類已經(jīng)刪除了惠毁,看了2.0里的實(shí)現(xiàn)犹芹,一般是用Binder類或Environment類代替實(shí)現(xiàn)。
下面也說了鞠绰,org.springframework.boot.bind整個(gè)包都刪了腰埂,2.0的寬松綁定規(guī)則可以看上面的鏈接,即 new relaxed binding infrastructure蜈膨。RelaxedDataBinder類也是被Binder類代替實(shí)現(xiàn)屿笼。

Binding on static methods

While binding on static properties (using a static getter and setter pair) works in Spring Boot 1.x, we never really intended to provide such feature and it is no longer possible as of Spring Boot 2.

這說的應(yīng)該是給帶有 static 關(guān)鍵詞的變量 綁定配置屬性值(例如:springboot讀取yml配置綁定靜態(tài)屬性
)牺荠,官方不推薦這種做法。

@ConfigurationProperties Validation

It is now mandatory that your @ConfigurationProperties object is annotated with @Validated if you want to turn on validation.

屬性配置類里驴一,1.x版本不加@Validated注解休雌,但變量上有@NotNull等校驗(yàn)規(guī)則注解亦能執(zhí)行校驗(yàn),2.0版本開始必須加上@Validated注解才能執(zhí)行校驗(yàn)蛔趴。

Configuration Location

The behavior of the spring.config.location configuration has been fixed; it previously added a location to the list of default ones, now it replaces the default locations. If you were relying on the way it was handled previously, you should now use spring.config.additional-location instead.
讀取jar包外部配置用的颁井,比較奇特谢揪,還沒這樣用過丙笋,大家可以看下這篇文章spring.config.location與spring.config.additional-location的區(qū)別

Developing Web Applications

Embedded containers package structure

In order to support reactive use cases, the embedded containers package structure has been refactored quite extensively. EmbeddedServletContainer has been renamed to WebServer and the org.springframework.boot.context.embedded package has been relocated to org.springframework.boot.web.server. Correspondingly, EmbeddedServletContainerCustomizer has been renamed to WebServerFactoryCustomizer.
For example, if you were customizing the embedded Tomcat container using the TomcatEmbeddedServletContainerFactory callback interface, you should now use TomcatServletWebServerFactory and if you were using an EmbeddedServletContainerCustomizer bean, you should now use a WebServerFactoryCustomizer<TomcatServletWebServerFactory> bean.

為了支持響應(yīng)式編程著恩,對包做了重構(gòu),WebServer新增了NettyWebServer和UndertowWebServer響應(yīng)式類的web server箫荡。WebServerFactoryCustomizer也相應(yīng)增加了一些實(shí)現(xiàn)類魁亦。

Servlet-specific server properties

A number of server.* properties that are Servlet-specific have moved to server.servlet:

配置屬性名稱變化.png
Web Starter as a Transitive Dependency

Previously several Spring Boot starters were transitively depending on Spring MVC with spring-boot-starter-web. With the new support of Spring WebFlux, spring-boot-starter-mustache, spring-boot-starter-freemarker and spring-boot-starter-thymeleaf are not depending on it anymore. It is the developer’s responsibility to choose and add spring-boot-starter-web or spring-boot-starter-webflux.

因?yàn)閟pring-boot-starter-webflux的出現(xiàn),spring-boot-starter-freemarker等依賴不再包含spring-boot-starter-web羔挡,由用戶自行引入選擇洁奈。

Template Engines
Thymeleaf

Spring Boot 2 uses Thymeleaf 3 which has its own migration guide.

In previous version of Spring Boot, the Thymeleaf starter included the thymeleaf-layout-dialect dependency previously. Since Thymeleaf 3.0 now offers a native way to implement layouts, we removed that mandatory dependency and leave this choice up to you. If your application is relying on the layout-dialect project, please add it explicitly as a dependency.

Thymeleaf 3 有了新的layout實(shí)現(xiàn),把方言依賴去掉了绞灼,需要的自己引入利术。

Mustache Templates Default File Extension

The default file extension for Mustache templates was .html, it is now .mustache to align with the official spec and most IDE plugins. You can override this new default by changing the spring.mustache.suffix configuration key.

改了文件后綴,可以通過配置屬性 spring.mustache.suffix 自定義。

Jackson / JSON Support

In 2.0, we’ve flipped a Jackson configuration default to write JSR-310 dates as ISO-8601 strings. If you wish to return to the previous behavior, you can add spring.jackson.serialization.write-dates-as-timestamps=true to your configuration.
A new spring-boot-starter-json starter gathers the necessary bits to read and write JSON. It provides not only jackson-databind but also useful modules when working with Java8: jackson-datatype-jdk8, jackson-datatype-jsr310 and jackson-module-parameter-names. If you were manually depending on those modules, you can now depend on this new starter instead.

JSR是指Java 規(guī)范提案低矮,JSR-310是關(guān)于java8的新日期時(shí)間API印叁,ISO-8601 是國際標(biāo)準(zhǔn)化組織提供的一個(gè)有關(guān)時(shí)間表示的規(guī)范,顯示如1970-01-01T00:00:00Z军掂。springboot2.0里jackson對新日期api序列化做了優(yōu)化轮蜕,差異可參考Spring Boot升級到2.x,Jackson對Date時(shí)間類型序列化的變化差異蝗锥,實(shí)現(xiàn)原理可參考jackson序列化配置跃洛。

Spring MVC Path Matching Default Behavior Change

We’ve decided to change the default for suffix path matching in Spring MVC applications (see #11105). This feature is not enabled by default anymore, following a best practice documented in Spring Framework.
If your application expects requests like "GET /projects/spring-boot.json" to be mapped to @GetMapping("/projects/spring-boot") mappings, this change is affecting you.
For more information about this and how to mitigate that change, check out the reference documentation about path matching and content negotiation in Spring Boot.

GET模式的http請求路徑匹配規(guī)則取消了后綴路徑匹配,如 "http://localhost:8080/test.xxx"不能映射到"http://localhost:8080/test"终议。

Servlet Filters

The default dispatcher types for a Servlet Filter are now DipatcherType.REQUEST; this aligns Spring Boot’s default with the Servlet specification’s default. If you wish to map a filter to other dispatcher types, please register your Filter using a FilterRegistrationBean.
Note:Spring Security and Spring Session filters are configured for ASYNC, ERROR, and REQUEST dispatcher types.

這個(gè)對于使用了Servlet Filters的應(yīng)用會(huì)有影響汇竭,可以參考SpringBoot1.5.12升級至2.1.9過程中,由DipatcherType引發(fā)的ShiroFilter失效問題穴张。

RestTemplateBuilder

The requestFactory(ClientHttpRequestFactory) method has been replaced by a new requestFactory(Supplier<ClientHttpRequestFactory> requestFactorySupplier) method. The use of a Supplier allows every template produced by the builder to use its own request factory, thereby avoiding side-effects that can be caused by sharing a factory. See #11255.

RestTemplateBuilder是一個(gè)可用于配置和創(chuàng)建RestTemplate的生成de器细燎。提供便捷方法去注冊converters, error handlers和UriTemplateHandlers。

WebJars Locator

Spring Boot 1.x used and provided dependency management for org.webjars:webjars-locator. webjars-locator is a "poorly named library … that wraps the webjars-locator-core project". Dependencies on org.webjars:webjars-locator should be updated to use org.webjars:webjars-locator-core instead.

WebJars是將web前端資源(js陆馁,css等)打成jar包文件找颓,現(xiàn)在都是前后端分離了合愈,應(yīng)該沒什么人會(huì)用了把叮贩。

Custom DispatcherServlet registration

If you have customized the registration of the DispatcherServlet, by providing a ServletRegistrationBean named dispatcherServletRegistration, you must also provide a DispatcherServletPath bean so that other components can be aware of the dispatcher servlet’s path. One way to do so is to provide a DispatcherServletRegistrationBean, which implements DispatcherServletPath rather than a ServletRegistrationBean when customizing the registration.

ServletRegistrationBean是將Servlet注冊到spring用的击狮,沒看懂這段話什么意思。

Security

Tip:This section provides a summary of the changes to security in Spring Boot 2. If you want to know more, refer to the Security migration use cases wiki page.

Spring Boot 2 greatly simplifies the default security configuration and makes adding custom security easy. Rather than having several security-related auto-configurations, Spring Boot now has a single behavior that backs off as soon as you add your own WebSecurityConfigurerAdapter.
You are affected if you were using any of the following properties:

security.basic.authorize-mode
security.basic.enabled
security.basic.path
security.basic.realm
security.enable-csrf
security.headers.cache
security.headers.content-security-policy
security.headers.content-security-policy-mode
security.headers.content-type
security.headers.frame
security.headers.hsts
security.headers.xss
security.ignored
security.require-ssl
security.sessions
Default Security

The security auto-configuration no longer exposes options and uses Spring Security defaults as much as possible. One noticeable side effect of that is the use of Spring Security’s content negotiation for authorization (form login).
Spring Boot 2.0 doesn’t deviate too much from Spring Security’s defaults, as a result of which some of the endpoints that bypassed Spring Security in Spring Boot 1.5 are now secure by default. These include the error endpoint and paths to static resources such as /css/**, /js/**, /images/**, /webjars/**, /**/favicon.ico. If you want to open these up, you need to explicitly configure that.

springboot2.0默認(rèn)配置了安全屬性益老,可以通過繼承WebSecurityConfigurerAdapter自定義安全配置彪蓬。

Default User

Spring Boot configures a single user with a generated password, by default. The user can be configured using properties under spring.security.user.*. To customize the user further or add other users, you will have to expose a UserDetailsService bean instead. This sample demonstrates how to do it.

在SecurityProperties類中定義了默認(rèn)用戶的屬性,可以通過屬性配置或者注冊InMemoryUserDetailsManager Bean捺萌,替換默認(rèn)實(shí)現(xiàn)生成自定義的用戶档冬。

To disable default user creation, provide a bean of type AuthenticationManager, AuthenticationProvider or UserDetailsService.
Note:Autowiring an AuthenticationManagerBuilder into a method in a configuration class does not disable creation of the default user.

一般來說,正常應(yīng)用都是從數(shù)據(jù)庫或其他地方讀取用戶信息桃纯,而不是一個(gè)默認(rèn)用戶酷誓。參考AuthenticationManager、AuthenticationProvider态坦、UserDetailsService的關(guān)系與區(qū)別了解AuthenticationManager, AuthenticationProvider和UserDetailsService盐数。

AuthenticationManager Bean

If you want to expose Spring Security’s AuthenticationManager as a bean, override the authenticationManagerBean method on your WebSecurityConfigurerAdapter and annotate it with @Bean.

如果想要將AuthenticationManager聲明為Bean,需要覆寫WebSecurityConfigurerAdapter類的authenticationManagerBean方法伞梯,再加上@Bean注解玫氢。

OAuth2

Functionality from the Spring Security OAuth project is being migrated to core Spring Security. Dependency management is no longer provided for that dependency and Spring Boot 2 provides OAuth 2.0 client support via Spring Security 5.
If you depend on Spring Security OAuth features that have not yet been migrated, you will need to add a dependency on an additional jar, check the documentation for more details. We’re also continuing to support Spring Boot 1.5 so older applications can continue to use that until an upgrade path is provided.

依賴合并,沒什么好說的谜诫。

Actuator Security

There is no longer a separate security auto-configuration for the Actuator (management.security.* property are gone). The sensitive flag of each endpoint is also gone to make things more explicit in the security configuration. If you were relying to this behavior, you need to create or adapt your security configuration to secure endpoints with the role of your choice.
For instance, assuming the following config

endpoints.flyway.sensitive=false
endpoints.info.sensitive=true
management.security.roles=MY_ADMIN

這是配置監(jiān)控端點(diǎn)安全的漾峡,這些配置屬性已經(jīng)不能用了。

http
    .authorizeRequests()
    .requestMatchers(EndpointRequest.to("health", "flyway")).permitAll()
        .requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("MY_ADMIN")
        ...

可以通過繼承WebSecurityConfigurerAdapter類實(shí)現(xiàn)喻旷,參考SpringBoot之Actuator生逸。

Note that in 2.x, health and info are enabled by default (with health details not shown by default). To be consistent with those new defaults, health has been added to the first matcher.

Working with SQL Databases

Spring Data Kay renamed a number of its CRUD repository methods. Application code calling the renamed methods will have to be updated. To ease the migration, you may want to consider using a custom CrudRepository sub-interface that declares deprecated default methods that use the old names and delegate to the equivalent newly named method. Marking the default methods has deprecated will help to ensure that the migration is not forgotten.

我也不知道什么方法重命名了,找不到掰邢,無語牺陶。

Configuring a DataSource

The default connection pool has switched from Tomcat to HikariCP. If you used spring.datasource.type to force the use of Hikari in a Tomcat-based application, you can now remove that override.

默認(rèn)數(shù)據(jù)源已切換到HikariCP,不需要再用配置屬性強(qiáng)制指定辣之。

In particular, if you had such setup:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jdbc</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
</dependency>

you can now replace it with:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

跟上面一樣的意思掰伸,已經(jīng)默認(rèn)加了。

WARN Message for Implicit 'open-in-view'

From now on, applications that don’t explicitly enable spring.jpa.open-in-view will get a WARN message during startup. While this behavior is a friendly default, this can lead to issues if you’re not fully aware of what’s that doing for you. This message makes sure that you understand that database queries may be performed during view rendering. If you’re fine with that, you can configure explicitly this property to silence the warning message.

沒有顯式配置則默認(rèn)為true怀估,應(yīng)用啟動(dòng)時(shí)打印warn日志狮鸭。這個(gè)屬性的作用是添加一個(gè)攔截器OpenEntityManagerInViewInterceptor,它會(huì)改變Session的創(chuàng)建時(shí)機(jī)和事務(wù)的范圍多搀,可以參考JPA的使用總結(jié)歧蕉。

JPA

In Spring Boot 1.x, some users were extending from HibernateJpaAutoConfiguration to apply advanced customizations to the auto-configured EntityManagerFactory. To prevent such faulty use case from happening, it is no longer possible to extend from it in Spring Boot 2.

應(yīng)該是指org.hibernate.jpa.HibernateEntityManagerFactory過期了的事。

To support those use cases, you can now define a HibernatePropertiesCustomizer bean that gives you full control over Hibernate properties, including the ability to register Hibernate interceptor declared as beans in the context.

應(yīng)該是要實(shí)現(xiàn)HibernatePropertiesCustomizer接口康铭,聲明注解@Configuration惯退,沒有實(shí)踐過。

Id generator

The spring.jpa.hibernate.use-new-id-generator-mappings property is now true by default to align with the default behaviour of Hibernate. If you need to temporarily restore this now deprecated behaviour, set the property to false.

use-new-id-generator-mappings以前默認(rèn)為false从藤,現(xiàn)在默認(rèn)為true催跪,是用來判斷選擇主鍵生成策略的锁蠕,可以參考# SequenceStyleGenerator MySQL 使用注意事項(xiàng)

Flyway

Flyway configuration keys were moved to the spring namespace (i.e. spring.flyway)
Upgrading to Spring Boot 2 will upgrade Flyway from 3.x to 5.x. To make sure that the schema upgrade goes smoothly, please follow the following instructions:

  • First upgrade your 1.5.x Spring Boot application to Flyway 4 (4.2.0 at the time of writing), see the instructions for Maven and Gradle.
  • Once your schema has been upgraded to Flyway 4, upgrade to Spring Boot 2 and run the migration again to port your application to Flyway 5.

If you experience a checksum error on upgrading the schema (i.e. FlywayException: Validate failed. Migration Checksum mismatch), invoking repair could help as show in the following example
Tip:Alternatively, this blog post by @wimdeblauwe provides a different approach that saves the two step upgrade.

@Bean
public FlywayMigrationStrategy repairStrategy() {
    return flyway -> {
        flyway.repair();
        flyway.migrate();
    };
}

Flyway 數(shù)據(jù)庫版本控制的組件,第一次見識(shí)懊蒸。參考介紹Flyway 數(shù)據(jù)庫版本控制荣倾。
增加了配置屬性的前綴spring。

Liquibase

Liquibase configuration keys were moved to the spring namespace (i.e. spring.liquibase)

增加了配置屬性的前綴spring骑丸。

Liquibase

Liquibase configuration keys were moved to the spring namespace (i.e. spring.liquibase)

Liquibase 也是數(shù)據(jù)庫版本控制的組件舌仍,同樣沒用過。參考介紹數(shù)據(jù)庫版本控制-liquibase

Database Initialization

Basic DataSource initialization is now only enabled for embedded data sources and will switch off as soon as you’re using a production database. The new spring.datasource.initialization-mode (replacing spring.datasource.initialize) offers more control.

這個(gè)屬性是用來判斷是否執(zhí)行初始化sql的通危。拓展知識(shí)springboot 啟動(dòng)時(shí)初始化數(shù)據(jù)庫的步驟

Updated Default 'create-drop' Handling

The spring.jpa.hibernate.ddl-auto property defaults to create-drop with an embedded database only if no schema manager, such as Liquibase or Flyway, is in use. As soon as a schema manager is detected, the default changes to none.

spring.jpa.hibernate.ddl-auto 實(shí)際對應(yīng)屬性 hibernate.hbm2ddl.auto铸豁,用來控制表結(jié)構(gòu)的更改,甚至創(chuàng)建和刪除菊碟。當(dāng)連接嵌入式數(shù)據(jù)庫時(shí)推姻,默認(rèn) create-drop,其他默認(rèn)none框沟。
拓展知識(shí)Spring Boot初始化數(shù)據(jù)庫和導(dǎo)入數(shù)據(jù)以及spring.jpa.generate-dll與spring.jpa.hibernate.ddl-auto之間的困惑藏古。

Working with NoSQL Technologies

Redis

Lettuce is now used instead of Jedis as the Redis driver when you use spring-boot-starter-data-redis. If you are using higher level Spring Data constructs you should find that the change is transparent.
We still support Jedis. Switch dependencies if you prefer Jedis by excluding io.lettuce:lettuce-core and adding redis.clients:jedis instead.

redis客戶端依賴Jedis默認(rèn)替換為Lettuce。

Connection pooling is optional and, if you are using it, you now need to add commons-pool2 yourself as Lettuce, contrary to Jedis, does not bring it transitively.

Jedis是直連redis的忍燥,所以一個(gè)請求對應(yīng)一次連接開關(guān)拧晕,比較消耗性能,所以配置連接池很有必要梅垄。Lettuce是基于netty的連接實(shí)例厂捞,不需要連接池也能共享連接,如果連接池使用不當(dāng)队丝,反而還會(huì)降低性能靡馁。拓展知識(shí)lettuce連接池真有必要嗎?机久。

Elasticsearch

Elasticsearch has been upgraded to 5.4+. In line with Elastic’s announcement that embedded Elasticsearch is no longer supported, auto-configuration of a NodeClient has been removed. A TransportClient can be auto-configured by using spring.data.elasticsearch.cluster-nodes to provide the addresses of one or more nodes to connect to.

官方不再支持嵌入式Elasticsearch 臭墨,因?yàn)樗@過了安全管理、插件加載等機(jī)制膘盖。節(jié)點(diǎn)配置方式發(fā)生了改變胧弛。

Caching

Dedicated Hazelcast Auto-configuration for Caching

It is no longer possible to auto-configure both a general HazelcastInstance and a dedicated HazelcastInstance for caching. As a result, the spring.cache.hazelcast.config property is no longer available.

Hazelcast是一個(gè)基于內(nèi)存的計(jì)算存儲(chǔ)平臺(tái),擅長流數(shù)據(jù)處理侠畔,沒用過结缚,不多做解釋。

GuavaCacheManager

Support for Guava has been dropped in Spring Framework 5. If you were are using GuavaCacheManager, Caffeine (com.github.ben-manes.caffeine:caffeine) and CaffeineCacheManager should be used instead.

在spring5中软棺,有以下幾種本地緩存實(shí)現(xiàn):
CaffeineCache:基于Caffeine組件實(shí)現(xiàn)红竭。
ConcurrentMapCache:基于java的ConcurrentMap實(shí)現(xiàn)。
EhCacheCache:基于EhCache組件實(shí)現(xiàn)。
JCacheCache:基于javax.cache實(shí)現(xiàn)茵宪。
NoOpCache:禁用緩存操作實(shí)現(xiàn)斥黑。這個(gè)實(shí)現(xiàn)的目的在于通過編寫配置的方式便捷切換緩存的使用與禁用,如@Profeile眉厨。
TransactionAwareCacheDecorator:緩存裝飾器,具體實(shí)現(xiàn)由注入的Cache決定兽狭。需要配合spring事務(wù)使用憾股,在事務(wù)提交后執(zhí)行cache操作,相當(dāng)于Read Committed級別箕慧。拓展知識(shí)TransactionAwareCacheDecorator升級版服球。

RedisCacheManager

The Redis CacheManager implementation has been reworked significantly, make sure to review the reference documentation.

RedisCacheManager被重寫了,現(xiàn)在可以將其配置為Bean颠焦,方便用戶自定義斩熊。

Batch

The CommandLineRunner that executes batch jobs on startup has an order of 0.

這是指實(shí)現(xiàn)類JobLauncherCommandLineRunner,現(xiàn)在實(shí)現(xiàn)了Ordered接口伐庭,默認(rèn)orderrder順序?yàn)?粉渠。

Testing

Mockito 1.x

Mockito 1.x is no longer supported for @MockBean and @SpyBean. If you don’t use spring-boot-starter-test to manage your dependencies you should upgrade to Mockito 2.x.
Note:See also What’s new in Mockito 2

沒用過Mockito,使用參考SpringBoot 單元測試詳解(Mockito圾另、MockBean)霸株。

EnvironmentTestUtils

EnvironmentTestUtils is deprecated in favour of TestPropertyValues that offers a similar, yet more powerful API as demonstrated in the following example:

TestPropertyValues.of("acme.first=1", "acme.second=2")
        .and("acme.third=3")
        .applyTo(this.environment);

EnvironmentTestUtils 應(yīng)替換為 TestPropertyValues。

Creating Your Own Auto-configuration

ConditionalOnBean semantic change

ConditionalOnBean is now using a logical AND rather than an OR for candidate beans. If you need to keep a condition where any of the target beans are present, consider using a AnyNestedCondition as shown in the following example:

class ThisOrThatCondition extends AnyNestedCondition {

    ThisOrThatCondition() {
        super(ConfigurationPhase.REGISTER_BEAN);
    }

    @ConditionalOnBean(This.class)
    static class ThisCondition {

    }

    @ConditionalOnBean(That.class)
    static class ThatCondition {

    }

}

ConditionalOnBean 的條件語義發(fā)生變化集乔,當(dāng)設(shè)置了多個(gè)類時(shí)去件,如@ConditionalOnBean(xxx.class,xxx.class),OR條件改為AND條件扰路。

Spring Boot Actuator

Spring Boot 2 brings important changes to the actuator, both internal and user-facing, please check the updated section in the reference guide and the new Actuator API documentation.

監(jiān)控平臺(tái)升級沒啥好說的尤溜,參考介紹springboot 的指標(biāo)監(jiān)控

Build

The code of the Actuator has been split in two modules: the existing spring-boot-actuator and a new spring-boot-actuator-autoconfigure. If you were importing the actuator using its original module (spring-boot-actuator), please consider using the spring-boot-starter-actuator starter instead.

actuator依賴升級汗唱,建議更換新的依賴宫莱。

Configuration Keys Structure

Endpoints infrastructure key have been harmonized:


配置屬性

配置屬性新老交替,替換下就好了哩罪。

Base Path

All endpoints have moved to /actuator by default.
We fixed the meaning of management.server.servlet.context-path: it is now the endpoint management equivalent of server.servlet.context-path (only active when management.server.port is set). Additionally, you can also set the base path for the management endpoints with a new, separate property: management.endpoints.web.base-path.
For example, if you’ve set management.server.servlet.context-path=/management and management.endpoints.web.base-path=/application, you’ll be able to reach the health endpoint at the following path: /management/application/health.

actuator 的端點(diǎn)基礎(chǔ)路徑默認(rèn)為 /actuator梢睛,如http://localhost:8080/actuator/health;當(dāng) management.endpoints.web.base-path=/manage识椰,那么http://localhost:8080/manage/health绝葡;當(dāng)management.server.servlet.context-path=/management 單獨(dú)使用,無法生效腹鹉,要加上 management.server.port=8082藏畅,如http://localhost:8082/management/actuator/health;當(dāng) management.endpoints.web.base-path=/application,那么 http://localhost:8082/application/health愉阎;三條屬性同時(shí)配置绞蹦,那么 http://localhost:8082/management/application/health

If you want to restore the behavior of 1.x (i.e. having /health instead of /actuator/health), set the following property:

management.endpoints.web.base-path=/

通過此配置榜旦,可以還原到actuator 1.x的路徑格式幽七。

Audit Event API Change

AuditEventRepository now has a single method with all optional arguments.

AuditEventRepository 用來添加AuditEvent的。AuthenticationAuditListener定義了三個(gè)事件用于監(jiān)聽溅呢,AUTHENTICATION_SUCCESS澡屡、AUTHENTICATION_FAILURE、AUTHENTICATION_SWITCH咐旧,并要求配合spring security使用驶鹉。用戶可以在端點(diǎn) /auditevents 下查看審計(jì)事件。參考Springboot Actuator之十:actuator中的audit包Spring Boot Actuator铣墨。

Endpoints

To make an actuator endpoint available via HTTP, it needs to be both enabled and exposed. By default:

  • Only the /health and /info endpoints are exposed, regardless of Spring Security being present and configured in your application.
  • All endpoints but /shutdown are enabled.

端點(diǎn)需要啟用并公開才能訪問室埋,默認(rèn)只公開 /health 和 /info,除 /shutdown 外其他端點(diǎn)都是啟用的伊约。

You can expose all endpoints as follows:

management.endpoints.web.exposure.include=*

公開所有端點(diǎn)姚淆。

You can explicitly enable the /shutdown endpoint with:

management.endpoint.shutdown.enabled=true

啟用 /shutdown 端點(diǎn)。

To expose all (enabled) web endpoints but the env endpoint:

management.endpoints.web.exposure.include=*
management.endpoints.web.exposure.exclude=env

公開除env端點(diǎn)之外的所有(已啟用)web端點(diǎn)屡律。


端點(diǎn)變更

Endpoint properties have changed as follows:

  • endpoints.<id>.enabled has moved to management.endpoint.<id>.enabled
  • endpoints.<id>.id has no replacement (the id of an endpoint is no longer configurable)
  • endpoints.<id>.sensitive has no replacement (See Actuator Security)
  • endpoints.<id>.path has moved to management.endpoints.web.path-mapping.<id>

端點(diǎn)配置屬性變化肉盹。

Endpoint Format

Overhaul of the "/actuator/mappings" Actuator Endpoint

The JSON format has changed to now properly include information about context hierarchies, multiple DispatcherServlets, deployed Servlets and Servlet filters. See #9979 for more details.
The relevant section of the Actuator API documentation provides a sample document.

/mappings 端點(diǎn)可以查看 @RequestMapping 下的請求路徑映射的json列表,2.x的json格式變了疹尾,看不出有啥影響上忍。

Overhaul of the "/actuator/httptrace" Actuator Endpoint

The structure of the response has been refined to reflect the endpoint’s focus on tracing HTTP request-response exchanges. More details about the endpoint and its response structure can be found in the relevant section of the Actuator API documentation.

/httptrace 端點(diǎn)可以查看http請求信息,2.x的json格式變了纳本。

Migrate Custom Endpoints

If you have custom actuator endpoints, please check out the dedicated blog post. The team also wrote a wiki page that describes how to migrate your existing Actuator endpoints to the new infrastructure.

1.x和2.x的端點(diǎn)實(shí)現(xiàn)方式變了很多窍蓝,參考actuator 2.x 自定義實(shí)現(xiàn)端點(diǎn)

Metrics

Spring Boot’s own metrics have been replaced with support, including auto-configuration, for Micrometer and dimensional metrics.

Setting up Micrometer

If your Spring Boot 2.0 application already depends on Actuator, Micrometer is already here and auto-configured. If you wish to export metrics to an external registry like Prometheus, Atlas or Datadog, Micrometer provides dependencies for many registries; you can then configure your application with spring.metrics.* properties to export to a particular registry.
For more on this, check out the Micrometer documentation about Spring Boot 2.0.

Micrometer 是一個(gè)基于 JVM 的應(yīng)用程序指標(biāo)收集工具包繁成,提供了抽象接口和脫離底層的第三方監(jiān)控依賴吓笙,類似于 SLF4J 在 Java 日志中的作用。參考介紹Spring Boot集成Micrometer巾腕。

Migrating Custom Counters/Gauges

Instead of injecting CounterService or GaugeService instances in your application code, you can create various metrics by:

可以參考上面的鏈接文章面睛。

Spring Boot 1.5 Support

You can plug existing Spring Boot 1.5 applications in the same metrics infrastructure by using the Micrometer Legacy support.

網(wǎng)站打不開,后面再看尊搬。

Developer Tools

Hot swapping

As the Spring Loaded project has been moved to the attic, its support in Spring Boot has been removed. We advise to use Devtools instead.

Spring Loaded項(xiàng)目被擱置叁鉴,推薦spring-boot-devtools。
Spring Loaded自2017年9月后佛寿,版本就沒有升級過了幌墓,看來是被放棄了。

Devtools Remote Debug Tunnel

The support for tunnelling remote debugging over HTTP has been removed from Devtools.

devtools 通過 HTTP 進(jìn)行遠(yuǎn)程調(diào)試,這個(gè)功能被刪除了常侣。

Removed Features

The following features are no longer available:

  • CRaSH support
  • Auto-configuration and dependency management for Spring Mobile.
  • Auto-configuration and dependency management for Spring Social. Please check the Spring Social project for more details.
  • Dependency management for commons-digester.
  • Test support in the CLI (i.e. spring test)

CRaSH support:遠(yuǎn)程執(zhí)行命令蜡饵。
Auto-configuration and dependency management for Spring Mobile:spring-mobile是基于模板引擎開發(fā)的框架,在前后端分離趨勢下胳施,項(xiàng)目廢棄是理所當(dāng)然的溯祸。
Auto-configuration and dependency management for Spring Social. Please check the Spring Social project for more details:為什么放棄spring social項(xiàng)目及替代方案
Dependency management for commons-digester:ommons-digester工具包的作用是將xml轉(zhuǎn)換為java對象舞肆。
Test support in the CLI (i.e. spring test):我的理解是spring-test不支持spring-boot-CLI焦辅。Spring Boot CLI是Spring Boot的命令行界面,使用groovy語言編寫胆绊,它可以用來快速啟動(dòng)Spring。

Dependency Versions

The minimum supported version of the following libraries has changed:

  • Elasticsearch 5.6
  • Gradle 4
  • Hibernate 5.2
  • Jetty 9.4
  • Spring Framework 5
  • Spring Security 5
  • Spring Integration 5 (see also their migration guide)
  • Tomcat 8.5

最小依賴版本支持欧募。

總結(jié)

這篇文章的編寫耗時(shí)超過了我的預(yù)期压状,涉及知識(shí)點(diǎn)廣泛,想要盡可能地理解每一點(diǎn)跟继,需要花不少時(shí)間种冬,即使如此,依然有很多理解偏頗(希望有人能指正)舔糖。不過寫完后娱两,發(fā)現(xiàn)自己也的確有所收獲。不管在面試還是日常工作中金吗,我們都需要知道自己所用何物十兢,才能物盡其用,所以當(dāng)工具發(fā)生變化時(shí)摇庙,及時(shí)了解變化之所在旱物,是很有必要的。

遷移指南中文翻譯

https://blog.51cto.com/u_14299052/2935938

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末卫袒,一起剝皮案震驚了整個(gè)濱河市宵呛,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌夕凝,老刑警劉巖宝穗,帶你破解...
    沈念sama閱讀 207,248評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異码秉,居然都是意外死亡逮矛,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,681評論 2 381
  • 文/潘曉璐 我一進(jìn)店門转砖,熙熙樓的掌柜王于貴愁眉苦臉地迎上來橱鹏,“玉大人,你說我怎么就攤上這事±蚶迹” “怎么了挑围?”我有些...
    開封第一講書人閱讀 153,443評論 0 344
  • 文/不壞的土叔 我叫張陵,是天一觀的道長糖荒。 經(jīng)常有香客問我杉辙,道長,這世上最難降的妖魔是什么捶朵? 我笑而不...
    開封第一講書人閱讀 55,475評論 1 279
  • 正文 為了忘掉前任蜘矢,我火速辦了婚禮,結(jié)果婚禮上综看,老公的妹妹穿的比我還像新娘品腹。我一直安慰自己,他們只是感情好红碑,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,458評論 5 374
  • 文/花漫 我一把揭開白布舞吭。 她就那樣靜靜地躺著,像睡著了一般析珊。 火紅的嫁衣襯著肌膚如雪羡鸥。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,185評論 1 284
  • 那天忠寻,我揣著相機(jī)與錄音惧浴,去河邊找鬼。 笑死奕剃,一個(gè)胖子當(dāng)著我的面吹牛衷旅,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播纵朋,決...
    沈念sama閱讀 38,451評論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼芜茵,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了倡蝙?” 一聲冷哼從身側(cè)響起九串,我...
    開封第一講書人閱讀 37,112評論 0 261
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎寺鸥,沒想到半個(gè)月后猪钮,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,609評論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡胆建,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,083評論 2 325
  • 正文 我和宋清朗相戀三年烤低,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片笆载。...
    茶點(diǎn)故事閱讀 38,163評論 1 334
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡扑馁,死狀恐怖涯呻,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情腻要,我是刑警寧澤复罐,帶...
    沈念sama閱讀 33,803評論 4 323
  • 正文 年R本政府宣布,位于F島的核電站雄家,受9級特大地震影響效诅,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜趟济,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,357評論 3 307
  • 文/蒙蒙 一乱投、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧顷编,春花似錦戚炫、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,357評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至层宫,卻和暖如春杨伙,著一層夾襖步出監(jiān)牢的瞬間其监,已是汗流浹背萌腿。 一陣腳步聲響...
    開封第一講書人閱讀 31,590評論 1 261
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留抖苦,地道東北人毁菱。 一個(gè)月前我還...
    沈念sama閱讀 45,636評論 2 355
  • 正文 我出身青樓,卻偏偏與公主長得像锌历,于是被迫代替她去往敵國和親贮庞。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,925評論 2 344

推薦閱讀更多精彩內(nèi)容