本文主要參考官文文檔。主要目的方便版本升級使用复凳,對于需要升級部分進行翻譯溯乒,對于新增特性等后續(xù)部分未做處理
1杠娱、Upgrading from Spring Boot 2.5
1.1 在Spring Boot 2.4棄用的代碼
在Spring Boot 2.4中棄用的類、方法和屬性將在這個版本中被移除。升級前請確保沒有使用被棄用注解的方法胚迫。
1.2 默認禁止循環(huán)引用
缺省情況下,現(xiàn)在禁止bean之間的循環(huán)引用唾那。如果您的應(yīng)用程序由于' BeanCurrentlyInCreationException '而啟動失敗访锻,強烈建議您更新配置以打破依賴循環(huán)。如果不能這樣做闹获,可以通過設(shè)置spring.main.allow-circular-references=true
期犬,或者在SpringApplication
和SpringApplicationBuilder
上使用新的setter方法旭蠕。這將恢復2.5的行為并自動嘗試打破依賴循環(huán)丹墨。
1.3 基于PathPattern的Spring MVC路徑匹配策略
根據(jù)注冊的Spring MVC處理程序映射匹配請求路徑的默認策略已經(jīng)從 AntPathMatcher
變?yōu)?PathPatternParser
。使用PathPatternParser
時使鹅,不支持自定義調(diào)度servlet路徑(spring.mvc.servlet.path
)茎用。
如果你正在使用Spring Security遣总,你應(yīng)該檢查你的mvcMatchers
的使用睬罗,以確保你的匹配器繼續(xù)滿足你的需求。對于AntPathMatcher
, authorizeRequests.mvcMatchers("hello").permitAll()
'將授予對' /hello '的訪問權(quán)限旭斥。更精確地匹配 PathPatternParser
需要使用authorizeRequests.mvcMatchers("/hello").permitAll()
(注意前導/
)來代替容达。
如果你需要將默認值切換回AntPathMatcher
,你可以設(shè)置 spring.mvc.pathmatch.matching-strategy=ant-path-matcher
垂券。
執(zhí)行器端點現(xiàn)在也使用基于 PathPattern
的URL匹配花盐。注意,執(zhí)行器端點的路徑匹配策略不能通過配置屬性進行配置菇爪。如果您正在使用Actuator和Springfox算芯,這可能會導致應(yīng)用程序無法啟動。請參見Springfox本期的詳細信息凳宙。
1.4 Actuator Env InfoContributor默認禁用
缺省情況下熙揍,env
信息貢獻者現(xiàn)在是禁用的。該貢獻者公開了Spring Environment 中任何名稱以 info
開頭的屬性氏涩。如果您有任何以info
開頭的屬性届囚,并希望它們顯示在InfoEndpoint
中,請將management.info.env.enabled=true
是尖。
1.5 Application Startup
記錄到ApplicationStartup
的 spring.boot.application.running
啟動步驟已被重命名為spring.boot.application.ready
意系。如果你正在處理從FlightRecorderApplicationStartup
或 BufferingApplicationStartup
生成的文件,你將需要使用新的名稱饺汹。
1.6 Web資源配合
直接注入Resources
不再有效蛔添,因為這個配置已經(jīng)在WebProperties
中得到了協(xié)調(diào)。如果你需要訪問這些信息兜辞,你需要注入WebProperties
來代替迎瞧。
1.7 Dependency Management移除
JBoss Transaction SPI
Dependency management for org.jboss:jboss-transaction-spi
has been removed. If you are using org.jboss:jboss-transaction-spi
you should define your own dependency management that meets your application’s needs.
Nimbus DS
Dependency management for com.nimbusds:oauth2-oidc-sdk
and com.nimbusds:nimbus-jose-jwt
has been removed. If you are using Spring Security you should rely on the versions that it will pull in as transitive dependencies. If you are not using Spring Security you should define your own dependency management that meets your application’s needs.
HAL Browser
Dependency management for org.webjars:hal-browser
has been removed. If you are using org.webjars:hal-browser
you should define your own dependency management that meets your application’s needs.
1.8 Prometheus版本屬性
控制Prometheus版本的屬性已從prometheus-pushgateway.version
更改為prometheus-client.version
。這是為了反映出該屬性管理Prometheus客戶端中每個模塊的版本弦疮,而不僅僅是pushgateway夹攒。
1.9 嵌入式Mongo
要使用嵌入式mongo,spring.mongodb.embedded.version
必須設(shè)置的屬性胁塞。這有助于確保MongoDB 版本咏尝。這有助于確保嵌入式支持使用的MongoDB版本與您的應(yīng)用程序?qū)⒃谏a(chǎn)中使用的MongoDB版本相匹配。
1.10 Oracle數(shù)據(jù)庫驅(qū)動依賴管理
Oracle數(shù)據(jù)庫驅(qū)動程序的依賴管理已經(jīng)簡化啸罢。如果你仍然依賴舊的 com.oracle.ojdbc
groupId编检,你需要升級到 com.oracle.database.jdbc
groupId,因為我們已經(jīng)刪除了前者的依賴管理扰才。
1.11 Flyway Vault相關(guān)屬性移除
Flyway的7.12版本將vault相關(guān)的設(shè)置移到了一個閉源擴展中允懂。不幸的是,這妨礙了Spring Boot對它們進行配置衩匣。結(jié)果蕾总,對應(yīng)的spring.flyway.vault-secrets
, spring.flyway.vault-token
, 和spring.flyway.vault-url
的屬性已被刪除粥航。如果您是Flyway Teams用戶,可以通過FlywayConfigurationCustomizer
bean, FluentConfigiguration.getExtensionConfiguration
和Vault ApiExtension
配置設(shè)置生百。
1.12 WebFlux Session 屬性
spring.webflux.session
屬性組已棄用递雀,并已遷移到server.reactive.session
。舊的屬性將繼續(xù)工作蚀浆,但如果可能缀程,您應(yīng)該遷移到新的屬性。
1.13 Elasticsearch 屬性整合
用于配置Elasticsearch客戶端的配置屬性已經(jīng)得到了統(tǒng)一市俊。以前杨凑,配置阻塞高級REST客戶端和響應(yīng)式REST客戶機的許多常用屬性在 spring.elasticsearch.rest
和 spring.data.elasticsearch.clients.reactive
中重復。
如果您正在使用阻塞REST客戶端摆昧,下表列出了舊屬性及其替換項:
Deprecated Property | Replacement |
---|---|
spring.elasticsearch.rest.uris |
spring.elasticsearch.uris |
spring.elasticsearch.rest.username |
spring.elasticsearch.username |
spring.elasticsearch.rest.password |
spring.elasticsearch.password |
spring.elasticsearch.rest.connection-timeout |
spring.elasticsearch.connection-timeout |
spring.elasticsearch.rest.read-timeout |
spring.elasticsearch.socket-timeout |
spring.elasticsearch.rest.sniffer.interval |
spring.elasticsearch.restclient.sniffer.interval |
spring.elasticsearch.rest.sniffer.delay-after-failure |
spring.elasticsearch.restclient.sniffer.delay-after-failure If you are using the reactive client, the following table lists the old properties and their replacements: |
Deprecated Property | Replacement |
---|---|
spring.data.elasticsearch.client.reactive.endpoints |
spring.elasticsearch.uris |
spring.data.elasticsearch.client.reactive.use-ssl |
https scheme when configuring spring.elasticsearch.uris
|
spring.data.elasticsearch.client.reactive.username |
spring.elasticsearch.username |
spring.data.elasticsearch.client.reactive.password |
spring.elasticsearch.password |
spring.data.elasticsearch.client.reactive.connection-timeout |
spring.elasticsearch.connection-timeout |
spring.data.elasticsearch.client.reactive.socket-timeout |
spring.elasticsearch.socket-timeout |
spring.data.elasticsearch.client.reactive.max-in-memory-size |
spring.elasticsearch.webclient.max-in-memory-size |
1.14 Spring Data Couchbase不在考慮使用注解@Persistent
為了使默認行為與Spring Data Couchbase保持一致撩满, @Persistent
注解類型不再被考慮。如果您依賴于該注解据忘,則可以使用@Document
代替鹦牛。
1.15 Maven Build Info’s Default Time
Maven插件的構(gòu)建信息支持現(xiàn)在使用 project.build.outputTimestamp
屬性作為默認的構(gòu)建時間。如果未設(shè)置該屬性勇吊,則使用構(gòu)建會話的開始時間。和以前一樣窍仰,時間可以通過設(shè)置為off
來完全禁用汉规。
1.16 Records and @ConfigurationProperties
如果你在一個Java 16類中使用 @ConfigurationProperties
,并且該類只有一個構(gòu)造函數(shù)驹吮,那么它就不再需要用 @ConstructorBinding
注解了针史。如果你的類有多個構(gòu)造函數(shù), @ConstructorBinding
仍然應(yīng)該用來標識用于屬性綁定的構(gòu)造函數(shù)碟狞。
1.17 Deferred OpenID Connect Discovery
對于使用 spring-security-oauth2-resource-server
配置了OpenID連接issuer-uri
的資源服務(wù)器應(yīng)用程序啄枕,Spring Boot現(xiàn)在會自動配置SupplierJwtDecoder
而不是NimbusJwtDecoder
。這就啟用了Spring Security的惰性O(shè)IDC發(fā)現(xiàn)支持族沃,從而提高了啟動時間频祝。類似地,對于響應(yīng)式應(yīng)用程序脆淹,ReactiveSupplierJwtDecoder
是自動配置的常空。
1.18 Kafka 3.0
Spring Boot 2.6升級到Apache Kafka 3.0旨在默認啟用最強的交付保證。由于一個Kafka bug盖溺,這些更改直到Kafka 3.0.1 (Spring Boot 2.6.5使用Kafka 3.0.1)才完全到位漓糙。
啟用冪等會導致一些問題,例如在升級時出現(xiàn) ClusterAuthorizationException
烘嘱。如果你遇到問題昆禽,想要禁用冪等(Kafka 3.0.1之前的默認值)蝗蛙,設(shè)置以下屬性:
spring.kafka.producer.properties.enable.idempotence=false
1.19 最低要求的變化
無。
2醉鳖、New and Noteworthy
Check the configuration changelog for a complete overview of the changes in configuration. |
SameSite Cookie Attribute Servlet Support
You can now configure SameSite
attributes on session cookies for servlet applications using the server.servlet.session.cookie.same-site
property. This works with auto-configured Tomcat, Jetty and Undertow servers.
In addition, the CookieSameSiteSupplier
interface can be used if you want to apply a SameSite
attribute to other cookies. See the updated documentation for more details and some example code.
Reactive Server Session Properties
The session properties supported for reactive servers (previously under spring.webflux.session
) have been expanded with this release. The new properties are available under server.reactive.session
and now offer parity with the servlet versions.
Pluggable Sanitization Rules
Spring Boot sanitizes sensitive values present in the /env
and /configprops
endpoints. While it was possible to configure which properties get sanitized via configuration properties, users might want to apply sanitization rules based on which PropertySource
the property originated from. For example, Spring Cloud Vault uses vault to store encrypted values and load them into the Spring environment. Since all values are encrypted, it would make sense to blank the values of every key in an entire property source. Such sanitization customizations can be configured by adding a @Bean
of type SanitizingFunction
.
Java Runtime Information
The info
endpoint can now expose Java Runtime information under the java
key, as shown in the following example:
{
"java": {
"vendor": "BellSoft",
"version": "17",
"runtime": {
"name": "OpenJDK Runtime Environment",
"version": "17+35-LTS"
},
"jvm": {
"name": "OpenJDK 64-Bit Server VM",
"vendor": "BellSoft",
"version": "17+35-LTS"
}
}
}
To expose this information in the info
endpoint’s response, set the management.info.java.enabled
property to true
.
Build Info Property Exclusions
It’s now possible to exclude specific properties from being added to the build-info.properties
file generated by the Spring Boot Maven or Gradle plugin.
Maven users can exclude the standard group
, artifact
, name
, version
or time
properties using the <excludeInfoProperties>
tag. For example, to exclude the version
property the following configuration can be used:
<configuration>
<excludeInfoProperties>
<excludeInfoProperty>version</excludeInfoProperty>
</excludeInfoProperties>
</configuration>
Gradle users can use null
values with the properties
block of the DSL:
task buildInfo(type: org.springframework.boot.gradle.tasks.buildinfo.BuildInfo) {
destinationDir project.buildDir
properties {
version = null
}
}
Health Support
Additional Path on Main or Management Port
Health groups can be made available at an additional path on either the main or management port. This is useful in cloud environments such as Kubernetes, where it is quite common to use a separate management port for the actuator endpoints for security purposes. Having a separate port could lead to unreliable health checks because the main application might not work properly even if the health check is successful. A typical configuration would have all the actuator endpoints on a separate port and health groups that are used for liveness and readiness available at an additional path on the main port.
Composite Contributor Include/Exclude Support
Health groups can be configured to include/exclude parts of a CompositeHealthContributor
. This can be done by specifying the fully qualified path to the component. For example, a component spring
which is nested inside a composite named test
, can be included using test/spring
.
Metrics Support
Application Startup
Auto-configuration exposes two metrics related to application startup:
application.started.time
: time taken to start the application.application.ready.time
: time taken for the application to be ready to service requests.
Disk Space
Micrometer’s DiskSpaceMetrics
are now auto-configured. disk.free
and disk.total
metrics are provided for the partition identified by the current working directory. To change the path that is used, define your own DiskSpaceMetrics
bean.
Task Execution and Scheduling
Micrometer’s ExecutorServiceMetrics
are now auto-configured for all ThreadPoolTaskExecutor
and ThreadPoolTaskScheduler
beans, as long as the underlying ThreadPoolExecutor
is available. Metrics are tagged with the name of the executor derived from its bean name.
Jetty Connection and SSL
Micrometer’s JettyConnectionMetrics
are now auto-configured. Additionally, when server.ssl.enabled
is set to true
, Micrometer’s JettySslHandshakeMetrics
are also auto-configured.
Exporting to the Dynatrace v2 API
Support for exporting metrics to the Dynatrace v2 API has been added. With a local OneAgent running on the host, a dependency on io.micrometer:micrometer-registry-dynatrace
is all that is required. Without a local OneAgent, the management.metrics.export.dynatrace.uri
and management.metrics.export.dynatrace.api-token
properties must be configured. Other settings that are specific to the v2 API can be configured using the management.metrics.export.dynatrace.v2
properties. Please refer to the updated reference documentation for further details.
Docker Image Building Support
Additional Image Tags
The Maven and Gradle plugins now support applying additional tags to a generated image after it is built using a tags
configuration parameter.
See the updated Gradle and Maven reference documentation for more details.
Network Configuration
A network
configuration parameter has been added to the Maven plugin spring-boot:build-image
goal and the Gradle bootBuildImage
task. This parameter can be used to configure the network driver used by the container that runs the Cloud Native Buildpacks builder process.
Cache Configuration
The Maven and Gradle plugins now support customizing the names of the volumes used to cache layers contributed to a built image by buildpacks using buildCache
and launchCache
configuration parameters.
See the updated Gradle and Maven reference documentation for more details.
Auto-configuration for Spring Data Envers
Auto-configuration for Spring Data Envers is now provided. To use it, add a dependency on org.springframework.data:spring-data-envers
and update your JPA repositories to extend from RevisionRepository
.
Redis Connection Pooling
Redis (both Jedis and Lettuce) will now automatically enable pooling when commons-pool2
is on the classpath. Set spring.redis.jedis.pool.enabled
or spring.redis.lettuce.pool.enabled
to false
to disable pooling if required.
Auto-configuration for spring-rabbit-stream
Auto-configuration for Spring AMQP’s new spring-rabbit-stream
module has been added. A StreamListenerContainer
is auto-configured when the spring.rabbitmq.listener.type
property is set to stream
. The spring.rabbitmq.stream.*
properties can be used to configure access to the broker and spring.rabbitmq.listener.stream.native-listener
can be used to enable native listener support.
Support for PEM format in Kafka SSL Properties
Previously, Kafka only supported file-based key and trust stores for SSL. With KIP-651, it is now possible to use the PEM format. Spring Boot has added the following properties that allow configuring SSL certificates and private keys using the PEM format:
spring.kafka.ssl.key-store-key
spring.kafka.ssl.key-store-certificate-chain
spring.kafka.ssl.trust-store-certificates
Improved Configuration of the Maven Plugin’s Start Goal
The Maven Plugin’s start
goal has been made more configurable from the command line. Its wait
and maxAttempts
properties can be specified using spring-boot.start.wait
and spring-boot.start.maxAttempts
respectively.
Auto-configured Spring Web Service Server Tests
A new annotation, @WebServiceServerTest
, that can be used to test Web Service @Endpoint
beans has been introduced. The annotation creates a test slice containing @Endpoint
beans and auto-configures a MockWebServiceClient
bean that can be used to test your web service endpoints.
MessageSource-based Interpolation of Bean Validation Messages
The application’s MessageSource
is now used when resolving {parameters}
in constraint messages. This allows you to use your application’s messages.properties
files for Bean Validation messages. Once the parameters have been resolved, message interpolation is completed using Bean Validation’s default interpolator.
Using WebTestClient for Testing Spring MVC
Developers could use WebTestClient
to test WebFlux apps in mock environments, or any Spring web app against live servers. This change also enables WebTestClient
for Spring MVC in mock environments: classes annotated with @AutoConfigureMockMvc
can get injected a WebTestClient
. This makes our support complete, you can now use a single API to drive all your web tests!
Spring Integration PollerMetadata Properties
Spring Integration PollerMetadata
(poll unbounded number of messages every second) can now be customized with spring.integration.poller.*
configuration properties.
Support for Log4j2’s Composite Configuration
Log4j2’s composite configuration is now supported. To use it, configure the logging.log4j2.config.override
property with a comma-separated list of secondary configuration files that will override the main configuration. The main configuration is sourced from Spring Boot’s defaults, a well-known standard location such as log4j2.xml
, or the location specified by the logging.config
property as before.
Dependency Upgrades
Spring Boot 2.6 moves to new versions of several Spring projects:
Numerous third-party dependencies have also been updated, some of the more noteworthy of which are the following:
Commons DBCP 2.9
Commons Pool 2.11
SnakeYAML 1.29
Miscellaneous
Apart from the changes listed above, there have also been lots of minor tweaks and improvements including:
The failure analysis for a
NoSuchMethodError
now includes information about the location from which the calling class was loaded.A
ClientResourcesBuilderCustomizer
bean can now be defined to customize Lettuce’sClientResources
will retaining the default auto-configuration.Configuration properties for Flyway’s
detectEncoding
,failOnMissingLocations
, andignoreMigrationPatterns
configuration settings have been added.A custom
ResourceLoader
to be used by the application can be provided when creating aSpringApplicationBulder
.A
WebSessionIdResolver
can now be defined to customize the resolver that will be used by the auto-configuredWebSessionManager
.Any
RSocketConnectorConfigurer
beans are now automatically applied to the auto-configuredRSocketRequester.Builder
.spring-boot-configuration-processor
can now generate metadata for classes annotated with Lombok’s@Value
.A new
server.tomcat.reject-illegal-header
configuration property can be set to true to configure Tomcat to accept illegal headers.When using Stackdriver, labels can now be configured on the monitor resource by setting
management.metrics.export.stackdriver.resource-labels.*
configuration properties.@EntityScan
now supports comma-separated values in itsbasePackages
attribute.A new configuration property,
server.netty.idle-timeout
, that can be used to control Reactor Netty’s idle timeout has been added.The location from which Devtools loads its global settings can now be configured using the
spring.devtools.home
system property or theSPRING_DEVTOOLS_HOME
environment variable.The setter methods on
RabbitTemplateConfigurer
are nowpublic
The
heapdump
endpoint is now supported on OpenJ9 where it will produce a heap dump in PHD format.New configuration properties are now supported for multipart support in WebFlux, under
spring.webflux.multipart.*
Any
ContainerCustomizer
bean is now called to configure the auto-configured Spring AMQPMessageListenerContainer
Jackson’s default leniency can be configured using the
spring.jackson.default-leniency
property.Distribution statistic’s expiry and buffer length are now configurable.
Command Latency metrics for Lettuce are now auto-configured.
Disk space metrics can be configured with one or more paths using the
management.metrics.system.diskspace.paths
property.Users can take control over the Redis auto-configuration by providing a
RedisStandaloneConfiguration
bean.The URLs of all available data sources is now logged when the H2 console is auto-configured.
A new configuration property,
spring.integration.management.default-logging-enabled
, can be used to disable Spring Integration’s default logging by setting its value tofalse
.Auto-configuration for
UserDetailsService
will now back off in the presence of anAuthenticationManagerProvider
bean.
Deprecations in Spring Boot 2.6.0
AbstractDataSourceInitializer
has been deprecated in favor ofDataSourceScriptDatabaseInitializer
. Similarly, subclasses ofAbstractDataSourceInitializer
have been deprecated in favour of newDataSourceScriptDatabaseInitializer
-based equivalents.SpringPhysicalNamingStrategy
has been deprecated in favor of Hibernate 5.5’sCamelCaseToUnderscoresNamingStrategy
Three methods on
AbstractApplicationContextRunner
have been deprecated in favor of newRunnerConfiguration
-based equivalentsThe
started
andrunning
methods inSpringApplicationRunListener
have been replaced with versions that accept aDuration
.Constructors in
ApplicationStartedEvent
andApplicationReadyEvent
have been replaced with versions that accept aDuration
.The
EnvironmentEndpoint.sanitize
has been deprecated for removal.