本文主要參考官文文檔箫荡。主要目的方便版本升級使用粗截,對于需要升級部分進(jìn)行翻譯,對于新增特性等后續(xù)部分未做處理渐逃。
1、Upgrading from Spring Boot 2.3
1.1 版本格式變化
從Spring Boot 2.4開始七冲,對應(yīng)Spring Cloud版本按照新規(guī)則命名套耕,這意味著你應(yīng)該在build.gradle/pom.xml 文件中升級Spring Boot版本构灸,從2.3.5.RELEASE 到 2.4.0。
1.2 spring-boot-starter-test
中移除JUnit 5’s vintage engine
如果你升級到Spring Boot 2.4笋额,看到單元測試中編譯報(bào)錯元暴,類似org.junit.Test等JUnit類,是因?yàn)閟pring-boot-starter-test中移除依賴JUnit 5’s vintage engine兄猩。Vintage Engine允許JUnit 5運(yùn)行JUnit 4編寫的單元用例茉盏。 如果你不想遷移你的單元測試到JUnit 5鉴未,可以添加Vintage Engine依賴。參考如下Maven依賴:
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
如果你正在使用Gradle鸠姨,等效的配置如下例所示:
testImplementation("org.junit.vintage:junit-vintage-engine") {
exclude group: "org.hamcrest", module: "hamcrest-core"
}
1.3 配置文件處理(application properties and YAML files)
spring Boot 2.4已經(jīng)改變了 application.properties
和 application.yml
文件的處理方式铜秆。如果你只有一個簡單的 application.properties
或application.yml
文件,你的升級應(yīng)該是無縫的讶迁。然而连茧,如果你有一個更復(fù)雜的設(shè)置(配置文件特定的屬性或配置profile激活屬性),如果你想使用新特性添瓷,你可能需要做一些更改梅屉。
如果你只想要Spring Boot 2.3兼容的邏輯,你可以在application.properties
或 application.yml
文件中設(shè)置一個 spring.config.use-legacy-processing
屬性為 true
鳞贷。
1.4 配置數(shù)據(jù)導(dǎo)入
配置文件可以指定spring.config.location
和spring.config.import
(在此版本中引入)導(dǎo)入坯汤。如果文件或文件夾不存在,則會報(bào)錯搀愧;如避免報(bào)錯惰聂,可以加上optional:
前綴。
例如:例如,spring.config.location=optional:/etc/config/application.properties
咱筛。如果application.properties
文件不存在搓幌,則忽略。
如果你想把所有的位置都當(dāng)作可選的迅箩,你可以設(shè)置 spring.config.on-not-found=ignore
在SpringApplication.setDefaultProperties(…)
或使用系統(tǒng)/環(huán)境變量溉愁。
1.5 嵌入數(shù)據(jù)庫檢測
嵌入式數(shù)據(jù)庫邏輯經(jīng)過了改進(jìn),只在數(shù)據(jù)庫位于內(nèi)存中時才認(rèn)為它是嵌入式的饲趋。如果您使用基于文件的持久性或H2拐揭、HSQL和Derby的服務(wù)器模式,則此更改會產(chǎn)生兩個后果:
- 不再設(shè)置
sa
用戶名奕塑。如果你依賴于這種行為堂污,你需要在您的配置中設(shè)置spring.datasource.username=sa
。 - 這樣的數(shù)據(jù)庫不會在啟動時被初始化龄砰,因?yàn)樗鼈儾辉俦徽J(rèn)為是嵌入式的盟猖。你可以像往常一樣使用`spring.datasource.initialization-mode進(jìn)行調(diào)優(yōu)。
1.6 不在支持用戶自定義MongoClientSettings
如果你使用自定義的MongoClientSettings
bean换棚,不在支持自動配置方式加載式镐。如果你依賴于這種行為,特別是與嵌入式Mongo的結(jié)合固蚤,考慮將定制器應(yīng)用到你自己的bean娘汞,如下例所示:
@Bean
public MongoClientSettings userDefinedMongoClientSettings(MongoProperties properties, Environment environment) {
MongoClientSettings.Builder builder = MongoClientSettings.builder();
//...
new MongoPropertiesClientSettingsBuilderCustomizer(properties, environment).customize(builder);
return builder.build();
}
1.7 Logback配置屬性
特定于Logback的Logging屬性已被重命名,以反映它們是特定于Logback的事實(shí)颇蜡,以前的名稱已被棄用价说。
以下Spring Boot屬性已被更改:
-
logging.pattern.rolling-file-name
→logging.logback.rollingpolicy.file-name-pattern
-
logging.file.clean-history-on-start
→logging.logback.rollingpolicy.clean-history-on-start
-
logging.file.max-size
→logging.logback.rollingpolicy.max-file-size
-
logging.file.total-size-cap
→logging.logback.rollingpolicy.total-size-cap
-
logging.file.max-history
→logging.logback.rollingpolicy.max-history
它們映射到的系統(tǒng)環(huán)境屬性也一樣:
-
ROLLING_FILE_NAME_PATTERN
→LOGBACK_ROLLINGPOLICY_FILE_NAME_PATTERN
-
LOG_FILE_CLEAN_HISTORY_ON_START
→LOGBACK_ROLLINGPOLICY_CLEAN_HISTORY_ON_START
-
LOG_FILE_MAX_SIZE
→LOGBACK_ROLLINGPOLICY_MAX_FILE_SIZE
-
LOG_FILE_TOTAL_SIZE_CAP
→LOGBACK_ROLLINGPOLICY_TOTAL_SIZE_CAP
-
LOG_FILE_MAX_HISTORY
→LOGBACK_ROLLINGPOLICY_MAX_HISTORY
1.8 默認(rèn)Servlet注冊
Spring Boot 2.4將不再注冊servlet容器提供的 DefaultServlet
。在大多數(shù)應(yīng)用程序中风秤,它不會被使用鳖目,因?yàn)镾pring MVC的 DispatcherServlet
'是唯一需要的servlet。你可以設(shè)置server.servlet.register-default-servlet
為 true
如果你仍然需要默認(rèn)的servlet缤弦。
1.9 默認(rèn)情況下领迈,HTTP traces不再包含cookie報(bào)頭
默認(rèn)情況下,Cookie
請求報(bào)頭和Set-Cookie
響應(yīng)報(bào)頭不再包含在HTTP traces中碍沐。要恢復(fù)Spring Boot 2.3的行為狸捅,設(shè)置 management.trace.http.include
為 cookies, errors, request-headers, response-headers
。
1.10 Undertow轉(zhuǎn)發(fā)時路徑
默認(rèn)情況下累提,Undertow在轉(zhuǎn)發(fā)請求時保留原始請求URL尘喝。這個版本覆蓋了默認(rèn)的Undertow以符合Servlet規(guī)范。以前的Undertow默認(rèn)行為可以通過設(shè)置屬性server.undertow.preserve-path-on-forward
為true來恢復(fù)斋陪。
1.11 Neo4j
這個版本對Neo4j支持進(jìn)行了重大改革朽褪。spring.data.neo4j.*
中的許多屬性已經(jīng)被移除,Neo4j OGM的支持也被移除无虚。
Neo4j驅(qū)動程序的配置是通過spring.neo4j.*
命名空間缔赠。雖然URI和來自data
命名空間的基本身份驗(yàn)證仍然以不贊成的方式支持。
有關(guān)此更改以及Spring Data Neo4j 6帶來的內(nèi)容的更多詳細(xì)信息友题,請查看文檔嗤堰。
1.12 Hazelcast 4
此版本升級到Hazelcast 4,同時保持與Hazelcast 3.2.x的兼容性度宦。如果你還沒有準(zhǔn)備好切換到Hazelcast 4踢匣,你可以使用hazelcast.version降級。
1.13 Elasticsearch RestClient
Spring Boot將不再自動配置初級的Elasticsearch RestClient bean斗埂。RestHighLevelClient bean仍然是自動配置的符糊。
大多數(shù)用戶不應(yīng)該需要使用初級的客戶端,也不應(yīng)該受到此更改的影響呛凶。
1.14 R2DBC
R2DBC的核心基礎(chǔ)設(shè)施已經(jīng)轉(zhuǎn)移到Spring Framework中的新的模塊 spring-r2dbc
中男娄。如果您正在使用此基礎(chǔ)設(shè)施,請確保將已棄用的訪問遷移到新的核心支持漾稀。
1.15 Flyway
Flyway 7的升級包括回調(diào)順序的一些更改模闲。這將是一個突破性的變化,任何人依賴注冊訂單崭捍,我們支持通過@Order
和 Ordered
尸折。
如果您正在使用Flyway 5,請確保在升級到Spring Boot 2.4之前升級到Flyway 6殷蛇,因?yàn)镕lyway只對一個特性版本進(jìn)行模式升級实夹。
1.16 移除maven插件flatten-maven-plugin
Spring Boot的構(gòu)建不再使用Flatten Maven Plugin (flatten-maven-plugin)橄浓,它的插件管理也被刪除了。如果你依賴Spring Boot的托管版本亮航,你應(yīng)該添加你自己的插件管理将塑。
1.17 移除maven插件exec-maven-plugin
exec-maven-plugin的版本管理已被刪除姊氓。如果您正在使用這個插件,請?jiān)谀腜luginManagement中指定一個版本。
1.18 Spring Boot Gradle Plugin
Spring引導(dǎo)Gradle插件bootJar
任務(wù)的DSL已經(jīng)更新盗冷,因此mainClass
可以使用Property<String>
進(jìn)行配置疟赊。如果你當(dāng)前使用的是mainClassName
楚午,例如:
bootJar {
mainClassName 'com.example.ExampleApplication'
}
你應(yīng)該把它改為 mainClass
:
bootJar {
mainClass 'com.example.ExampleApplication'
}
1.19 在集成測試中導(dǎo)出Metrics
@SpringBootTest
不再配置可用的監(jiān)控系統(tǒng)踪古,只提供內(nèi)存中的 MeterRegistry
。如果您將指標(biāo)作為集成測試的一部分導(dǎo)出钟沛,那么您可以在測試中添加 @AutoConfigureMetrics
以恢復(fù)之前的行為畔规。
1.20 Deprecations from Spring Boot 2.2 and 2.3
反映Spring Boot發(fā)布兼容策略, Spring Boot 2.2中已棄用的代碼已在Spring Boot 2.4\中刪除讹剔。在Spring Boot 2.3中已棄用的代碼仍然保留油讯,并計(jì)劃在Spring Boot 2.5中刪除。
2延欠、New and Noteworthy
Check the configuration changelog for a complete overview of the changes in configuration.
Spring Framework 5.3
Spring Boot 2.4 uses Spring Framework 5.3. The Spring Framework wiki has a what’s new section with details of the new release.
Spring Data 2020.0
Spring Boot 2.4 includes version 2020.0 (code-named Ockham) of the Spring Data release train. See the Spring Data wiki for release details.
Neo4j
This release brings support of reactive repositories and rely on a separate auto-configuration for the Neo4j driver. As a result, it is now possible to use Neo4j with or without Spring Data.
Health checks for Neo4j use the Driver and are available as long as the Neo4j driver is configured.
If you want to use @Transactional
with reactive access, you’d need to configure the Neo4jReactiveTransactionManager
bean yourself for now.
@Bean(ReactiveNeo4jRepositoryConfigurationExtension.DEFAULT_TRANSACTION_MANAGER_BEAN_NAME)
public ReactiveTransactionManager reactiveTransactionManager(Driver driver,
ReactiveDatabaseSelectionProvider databaseNameProvider) {
return new ReactiveNeo4jTransactionManager(driver, databaseNameProvider);
}
R2DBC
A R2dbcEntityTemplate
is available to simplify the use of Reactive R2DBC usage through entities
Java 15 Support
Spring Boot 2.4 now fully supports (and is tested against) Java 15. The minimum supported version remains Java 8.
Custom property name support
When using constructor binding the name of the property is derived from the parameter name. This can be a problem if you want to use a java reserved keyword. For such situations, you can now use the @Name
annotation, something like:
@ConfigurationProperties(prefix = "sample")
@ConstructorBinding
public class SampleConfigurationProperties {
private final String importValue;
public SampleConfigurationProperties(@Name("import") String importValue) {
this.importValue = importValue;
}
}
The sample above exposes a sample.import
property.
Layered jar enabled by default
This release enables layered jars and include the layertools by default. This should improve the efficiency of generated image using the build pack out-of-the-box and lets you benefit of that feature when crafting custom Dockerfile
.
Importing Additional Application Config
As long as you haven’t set spring.config.use-legacy-processing
to true
, you can now import additional properties and yaml files directly from your main application.properties
or application.yml
.
You can use the spring.config.import
property to specify one or more additional config files that should be imported into the Spring Environment
. See this section of the reference guide for more details.
We’ve published a short blog explaining why we’ve made these changes.
Volume Mounted Config Directory Trees
The spring.config.import
property can also be used to import configuration trees that are commonly used with Kubernetes. A configuration tree is an alternative way of providing key/value pairs. Each pair is declared in its own file, with the filename forming the property key, and the file contents providing the value.
For a complete example, see the updated reference documentation.
Properties loaded from config trees have trailing newline characters trimmed by default.
Importing Config Files That Have no File Extension
Some Cloud platforms only allow you to volume mount files without a file extension. If you have such a constraint, It’s now possible to import these files by providing a hint to Spring Boot about the content type. For example, spring.config.import=/etc/myconfig[.yaml]
will load /etc/myconfig
as YAML.
Origin Chains
The Origin
interface has been updated with a new getParent()
method. This allows us to provide a full origin chain that can show exactly where an item originated from.
For example, you might use spring.config.import
in your application.properties
to import a second file. The Origin
of properties loaded from this second file will have a parent that points back to the orginal import declaration.
You can try this yourself by looking at the output of the actuator/env
or actuator/configprops
actuator endpoints.
Startup Endpoint
A new startup
actuator endpoint is now available that shows information about your applications startup. The endpoint can help you identify beans that are taking longer than expected to start.
This work builds on the application startup tracking feature that was recently added to Spring Framwork 5.3. You can read more about the feature in the Spring Framework reference documentation.
The new actuator API is documented here.
Docker/Buildpack Support
Publishing Images
The Maven plugin spring-boot:build-image
goal and Gradle plugin bootBuildImage
task now have the ability to publish the generated image to a Docker registry. See the Maven and Gradle plugin documentation for more details on configuring the plugins for publishing images.
Authentication
When using Spring Boot’s buildpack support, you can now use a private authenticated Docker registry for your builder or run image. Both username/password and token based authentication are supported.
The Maven and Gradle documentation have been updated to show the new configuration.
Paketo Buildpack Defaults
The image builder used by the Maven plugin spring-boot:build-image
goal and Gradle plugin bootBuildImage
task by default has been upgraded to the latest Paketo images. The Paketo image registry has been changed from Google Container Registry to Docker Hub for improved accessibility.
Maven Buildpack Support
The spring-boot:build-image
Maven goal now puts all project modules dependencies in the "application" layer. This means that if you have multiple project modules in your build, they will now all end up in the same layer.
The XML schema has also been updated to allow the layer to be customized using new <includeModuleDependencies/>
and <excludeModuleDependencies/>
elements.
See the updated Maven documentation for details.
Gradle Buildpack Support
The bootBuildImage
Gradle task now puts all project modules dependencies in the "application" layer. This means that if you have multiple project modules in your build, they will now all end up in the same layer.
You can also use includeProjectDependencies()
and excludeProjectDependencies()
in the DSL when customizing layers.
See the updated Gradle documentation for details.
Redis Cache Metrics
If you’re using Redis caching you can now expose cache statistics via Micrometer. Metrics logged include the number puts, gets and deletes as well as hits/misses. The number of pending requests and the lock wait duration are also recorded.
To enable the feature, set spring.cache.redis.enable-statistics
to true
.
Web Configuration Properties
Properties have been added to support configuration of the web locale and resource locations with either Spring MVC or Spring WebFlux. The new properties are:
spring.web.locale
spring.web.locale-resolver
spring.web.resources.*
A new property has been added to support configuration of the actuators management endpoint with either the servlet or reactive web stack:
management.server.base-path
These Spring MVC and servlet specific properties have been deprecated in favor of the new properties that support either web stack:
spring.mvc.locale
spring.mvc.locale-resolver
spring.resources.*
management.server.servlet.context-path
Register @WebListeners in a way that allows them to register servlets and filters
Servlet @WebListener
classes are now registered in such a way that they may themselves register servlets and filters.
Earlier versions of Spring Boot registered them using a call to javax.servlet.Registration.Dynamic
. This meant that the following section of Servlet specification (4.4) applied:
If the ServletContext passed to the ServletContextListener’s contextInitialized method where the ServletContextListener was neither declared in web.xml or web-fragment.xml nor annotated with @WebListener then an UnsupportedOperationException MUST be thrown for all the methods defined in ServletContext for programmatic configuration of servlets, filters and listeners.
As of Spring Boot 2.4, we no longer use dynamic registration and so it’s safe to call event.getServletContext().addServlet(…)
and event.getServletContext.addFilter(…)
from a ServletContextListener.contextInitialized
method.
A side-effect of this change is that the Servlet container now creates the instance of the WebListener
and, therefore, dependency injection such as with @Autowired
can no longer be used. In such cases, @Component
should be used instead.
Slice Test for Cassandra
An additional test slice can be used to test components that rely on Cassandra using @DataCassandraTest
. As usual, only Cassandra Repositories and the required infrastructure is configured by default.
Here is an example using Testcontainers and @DynamicPropertSource
:
@DataCassandraTest(properties = "spring.data.cassandra.local-datacenter=datacenter1")
@Testcontainers(disabledWithoutDocker = true)
class SampleDataCassandraTestIntegrationTests {
@Container
static final CassandraContainer<?> cassandra = new CassandraContainer<>().withStartupAttempts(5)
.withStartupTimeout(Duration.ofMinutes(2));
@DynamicPropertySource
static void cassandraProperties(DynamicPropertyRegistry registry) {
registry.add("spring.data.cassandra.contact-points",
() -> cassandra.getHost() + ":" + cassandra.getFirstMappedPort());
}
...
}
Flyway 7
This release upgrades to Flyway 7 which brings some additional properties. For the open source edition we’ve add the following spring.flyway
properties:
url
user
password
If you’re using the "teams" edition you can also make use of:
cherry-pick
jdbc-properties
oracle-kerberos-cache-file
oracle-kerberos-config-file
skip-executing-migrations
Configuration property for H2 Console’s web admin password
A new configuration property, spring.h2.console.settings.web-admin-password
, for configuring H2 Console’s web admin password has been introduced. The password controls access to the console’s preferences and tools.
CqlSession-Based Health Indicators for Apache Cassandra
New CqlSession
based health indicators, CassandraDriverHealthIndicator
and CassandraDriverReactiveHealthIndicator
, have been introduced. One of these indicators will be auto-configured when Cassandra’s Java Driver is on the classpath. The existing Spring Data Cassandra-based health indicators have been deprecated.
Filtered Scraping with Prometheus
The Actuator’s Prometheus endpoint, /actuator/prometheus
, now supports an includedNames
query parameter that can be used to filter the samples that are included in the response. See the Actuator API documentation for further details.
Spring Security SAML Configuration Properties
Properties have been added to allow configuration of a SAML2 relying party registration’s decryption credentials and Assertion Consumer Service (ACS). The properties are under the following headings:
Failure Analyzers
FailureAnalizers will now be considered even if a ApplicationContext
was not created. This allows them to also analyze any exceptions thrown during Environment
processing.
Note that any analyzer that implements BeanFactoryAware
or EnvironmentAware
will not be used unless the ApplicationContext
was created.
Jar Optimizations
When generating runnable Spring Boot jars, empty starter dependencies will now be automatically removed. Since most starters only provide transitive dependencies, there is little point in packaging them in the final jar.
Spring Boot annotation processors are also removed as well as they are only useful during the build. These are spring-boot-autoconfigure-processor
and spring-boot-configuration-processor
.
If you have your own starter POMs that contain no code, you can add a Spring-Boot-Jar-Type
entry to its MANIFEST.MF with the value "dependencies-starter". If you want to filter out an annotation processor, you can add the same property with the value "annotation-processor".
Miscellaneous
Apart from the changes listed above, there have also been lots of minor tweaks and improvements including:
Version of the JVM on which the application is running is now logged on startup.
Trailing whitespace is automatically trimmed from the value of
logging.config
.R2DBC pool support exposes additional configuration properties.
Exception handling in
LdapTemplate
can be configured to ignore certain exceptions.ISO offset date time format is support for MVC and Webflux.
Add a configuration property to opt-in for the new
PathPatternParser
in lieu ofAntPathMatcher
to parse and match request mapping path patterns.@DurationUnit
,@DataSizeUnit
, and@PeriodUnit
can annotate a constructor parameter using@ConstructorBinding
.The auto-configured
RabbitConnectionFactory
checks for the presence ofCredentialsProvider
andCredentialsRefreshService
.A health group can be defined with only exclusions.
AbstractRoutingDataSource
can be ignored in health checks usingmanagement.health.db.ignore-routing-data-sources
.The localEntityIdTemplate of A SAML Relying party can be configured.
HTTP traces are measures with nanosecond precision.
A dedicated
FailureAnalyzer
provides a meaningful message when a Liquibase changelog is missing.Netty’s request decoder can be customized using
server.netty.*
properties.Plugin management for the Liquibase Maven Plugin that is consistent with the Liquibase version a Spring Boot version manages.
Basic authentication support for Prometheus PushGateway.
Allow selecting Jedis when both Jedis and Lettuce are available using
spring.redis.client-type
.Allow disabling Redis Cluster dynamic sources refresh using
spring.redis.lettuce.cluster.refresh.dynamic-sources
.The reference documentation now includes both
Properties
andYAML
for all configuration examples.RSocketServer’s fragment size can now be customized using the
spring.rsocket.fragment-size
property.The charsets used to by Logback and Log4j logging can now be configured using the properties
logging.charset.console
andlogging.charset.file
.Gradle’s configuration cache is supported when using Gradle 6.7 or later to build a Spring Boot application.
Dependency Upgrades
Spring Boot 2.4 moves to new versions of several Spring projects:
Spring AMQP 2.3 (what’s new)
Spring Batch 4.3 (what’s new)
Spring Data 2020.0 (changelog)
Spring Framework 5.3 (what’s new | upgrading)
Spring Integration 5.4 (what’s new)
Spring HATEOAS 1.2 (migration guide)
Spring Kafka 2.6 (what’s new)
Spring Retry 1.3
Spring Security 5.4 (what’s new)
Spring Session 2020.0
Numerous third-party dependencies have also been updated, some of the more noteworthy of which are the following:
Artemis 2.13
AssertJ 3.18
Elasticsearch 7.9
Flyway 7
Jersey 2.31
JUnit 5.7
Liquibase 3.10
Lettuce 6.0 (release notes)
Micrometer 1.6 (release notes)
Mockito 3.4
MongoDB 4.1
Oracle Database 19.7
Reactor 2020.0 (release notes)
RSocket 1.1
Undertow 2.2
Deprecations in Spring Boot 2.4
ConfigFileApplicationListener
has been deprecated in favor ofConfigDataEnvironmentPostProcessor
.SpringApplicationBuilder
andSpringApplication
methods relating to thecontextClass
have been deprecated in favor of alternatives that use acontextFactory
.Some methods of
CloudFoundryVcapEnvironmentPostProcessor
have been deprecated to work withEnvironmentPostProcessor
updates (these should affect most users).The
BuildLog
build pack support class has deprecated a few methods and replaced them with alternatives that provide more details.Logback constants in
LoggingSystemProperties
have been deprecated in favor ofLogbackLoggingSystemProperties
.The
isEagerInitFilters
/setEagerInitFilters
methods inUndertowServletWebServerFactory
have been replaced byisEagerFilterInit
/setEagerFilterInit
.A few methods from
ApplicationEnvironmentPreparedEvent
,ApplicationStartingEvent
andSpringApplicationRunListener
have been deprecated to supportBootstrapContext
.The
BuildLog
for buildpack support has been updated to support more data (most users will not directly use this class).Some Spring MVC and servlet specific properties have been deprecated (see the Web Configuration Properties section above).
Health indicators using Spring Data Cassandra have been deprecated in favour of the ones that are using the raw driver.