This commit introduces support for tracking operations during SpEL
expression evaluation. If the maximum number of operations is exceeded,
a SpelEvaluationException is thrown.
The limit can be configured either on a per-use-case basis via
SpelParserConfiguration supplied to the SpelExpressionParser or
globally as a JVM system property or Spring property named
`spring.expression.maxOperations`.
Closes gh-36801
This commit updates the default view name generation logic in
both Spring WebMVC and Spring WebFlux to prevent "redirect:"
and "forward:" (for MVC) prefixes from the incoming request path.
Closes gh-36793
This commit introduces trusted packages, specified via the related
setter for untrusted use cases. It allows explicit configuration
of which Java packages are allowed to be deserialized.
Closes gh-36791
This commit introduces trusted packages, specified via the related
setter for untrusted use cases. It allows explicit configuration
of which Java packages are allowed to be deserialized.
See gh-36791
CronTrigger carries an optional ZoneId since 5.3 that affects
nextExecution; however, prior to this commit, equals() and hashCode()
only considered the cron expression.
This commit ensures that CronTrigger instances with the same cron
expression but different time zones are no longer considered equal.
Closes gh-36871
Signed-off-by: zhaomeng <zhaomeng1.vendor@sensetime.com>
The links to docs.seleniumhq.org no longer resolve, since the host was
retired.
This commit changes those links to use the current Selenium
documentation at selenium.dev.
Closes gh-36875
Signed-off-by: leestana01 <leestana01@naver.com>
getClassName now calls ClassReader.getClassName() directly instead
of routing through the visitor-based getClassInfo. Previously, it
allocated a List and a ClassVisitor and decoded super_class and
every interface name only to discard all but the first element.
The method is on the hot path of every CGLIB proxy class definition,
so this change significantly lowers its per-call processing cost.
Closes gh-36814
Signed-off-by: cookie-meringue <daehyeon3351@gmail.com>
This commit adds further fixes in the same area, since there were
similar bugs in the WriteCompletionHandler:
* databuffers were not always emitted when fully read in the onNext hook
* on completion, the iterator was closed too early, before it was fully
read
* on completion, writing the next bytebuffers from the iterator would
always reuse the first one and not update the attachment
Closes gh-36714
Prior to this commit, WritableByteChannelSubscriber.hookOnNext() called
iterator.next() exactly once. If a DataBuffer consisted of multiple NIO
ByteBuffers (e.g., NettyDataBuffer wrapping a CompositeByteBuf), only
the first buffer was written to the channel, and the remaining buffers
were silently ignored and lost.
This commit adds the missing while (iterator.hasNext()) outer loop to
ensure all fragmented buffers exposed by the iterator are completely
and safely written to the synchronous channel.
See gh-36714
Signed-off-by: KimDaehyeon <daehyeon3351@gmail.com>
A disconnected client error does not necessarily prevent us from setting
the status of the WebFlux ServerHttpResponse, which is only gated by a
committed flag and does not necessarily reflect the connection state.
This is why we need to check if we have a disconnected client error
first and handle it accordingly. We still set the response to 500
in case the disconnect client error is to a remote host in which
case it will propagate to the client.
Closes gh-36811
DisconnectedClientHelper identifies lost connection issues, but it's
not always easy to know if it is the connection to the client or to
another remote host. DisconnectedClientHelper does recognize and
filter out common client exceptions, but there is a possibility for
other similar custom exceptions.
DefaultHandlerExceptionResolver now attempts to set the status to
500, which won't impact a client that has gone away, but it will
set the status correct on the off chance that the exception is
actually a server side issue.
Closes gh-34481
This fixes a potential regression introduced by the previous commit.
Because the current value was not updated after the temporal was rolled
forward, there were new cases where entire days would be skipped.
Closes gh-36865
After rollForward, BitsCronField always searched for the next
matching bit from zero. When daylight saving creates a gap at
the start of a period (e.g. Africa/Cairo), the temporal lands on
a non-zero field value and matching from zero could advance an
entire period too far, skipping the calendar day.
Search from the actual field value in the new period instead,
falling back to zero only when no bit matches in that period.
See gh-36865
Signed-off-by: arno <me@zmovo.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
The detectNumberOfBuffers() method attempted to scale the read
buffer count based on the number of available processors, but used
Math.min(4, nextPowerOfTwo) which effectively caps the result at 4
regardless of CPU count. For systems with fewer than 3 processors,
the buffer count would be reduced below 4, but this edge case adds
complexity without measurable benefit.
Simplify BUFFER_COUNT to a constant value of 4, removing the
unnecessary CPU-detection logic.
Closes gh-36872
Signed-off-by: seungchan <s24041@gsm.hs.kr>
Prior to this commit, comments sent with Server Sent Events could break
the wire format when sent over the network when comments contained line
breaks.
While comments are mainly used for sending keepalive messages, they can
also be used for sending debug data. This commit ensures that line
breaks are properly handled in comments.
Fixes gh-36866
DataBinder applies its auto-grow collection limit to bean
property access, but direct field access left DirectFieldAccessor
at its default limit.
Pass DataBinder's configured limit into DirectFieldBindingResult
and apply it to the DirectFieldAccessor.
Closes gh-36861
Signed-off-by: Matthias Kurz <m.kurz@irregular.at>
awaitEntity() used T::class.java which erases generic type
information (e.g. List<Foo> becomes just List). Use the
reified toEntity<T>() extension instead, which preserves
full generic type via ParameterizedTypeReference.
Closes gh-36834
Signed-off-by: wushiyuanmaimob <wushiyuanwork@outlook.com>
When parsing a relative URI such as `path2#foo`, RfcUriParser's
SCHEME_OR_PATH state advanced to FRAGMENT without moving the component
index past the `#` character, so the captured fragment included the
entire input (`path2#foo`) instead of just `foo`. As a result,
`toUriString()` produced `path2#path2#foo`.
Update the SCHEME_OR_PATH `#` transition to advance the component
index to `i + 1`, matching the sibling `?` -> QUERY transition in the
same state and every other `-> FRAGMENT` transition in the parser.
URIs with a `/` in the path are unaffected because they leave
SCHEME_OR_PATH for PATH on the first slash; the WhatWG parser already
handled this case correctly.
Closes gh-36762
Signed-off-by: daguimu <daguimu.geek@gmail.com>
Prior to this commit, the `antora` Gradle task silently failed to build
the reference documentation, since Antora uses the latest LTS release
for Node.js by default, and the latest LTS apparently does not work for
us.
Prior to this commit, MIME type parsing in Spring would allow duplicate
parameters like "text/plain; dupe=1; dupe=2", effectively retaining the
latest value and ignoring the first.
RFC 6838 4.3 states that this should be treated as an error and this
commit ensures that this is the case.
Closes gh-36841
Add a public accessor for the ClassLoader configured on a
DefaultDeserializer instance so that callers no longer need to read the
private field via reflection in order to forward it to a
ConfigurableObjectInputStream subclass.
See gh-36827
Closes gh-36833
Signed-off-by: seonwoo_jung <laborlawseon@kap.kr>
Prior to this commit, gh-36328 avoided using RFC 2047 encoding for the
"filename" parameter and use ISO-8859-1 only. This change unfortunately
caused issues because some implementations might try and detect the
encoding automatically.
This commit restricts the filename parameter to ASCII encoding only by:
* transliterating characters to the closes ASCII character
("é"->"e", "ä"->"ae"...)
* falling back to "_" for other chacacters with non latin alphabet or
emojis
Fixes gh-36805
Prior to this commit, it was not possible to specify the character set
to use with ExchangeFilterFunctions#basicAuthentication.
To address that, this commit introduces a new
Closes gh-36777
Signed-off-by: Kai Zander <61500114+kzander91@users.noreply.github.com>
Prior to this commit,
MicrometerObservationRegistryTestExecutionListener always attempted to
load the test's ApplicationContext in order to update the
ObservationThreadLocalAccessor in its beforeTestMethod() callback, even
if there was no active ApplicationContext.
To avoid unnecessarily loading an ApplicationContext or attempting to
load an ApplicationContext that cannot be loaded (for example, due to a
context-load failure), this commit applies a hasApplicationContext()
check in beforeTestMethod().
Since the MicrometerObservationRegistryTestExecutionListener is
registered after the DependencyInjectionTestExecutionListener (at least
by default), an active ApplicationContext should be present unless
dependency injection from the context failed or the context failed to
load.
Closes gh-36817
Prior to this commit and the previous commit,
MockitoResetTestExecutionListener always attempted to load the
ApplicationContext to reset mocks in its beforeTestMethod() and
afterTestMethod() callbacks, even if there was no active
ApplicationContext.
The reason this was noticed is that the @BeforeMethod(alwaysRun = true)
and @AfterMethod(alwaysRun = true) lifecycle methods in
AbstractTestNGSpringContextTests are always invoked, even if a previous
lifecycle configuration method failed (for example, due to a
context-load failure).
However, with JUnit Jupiter and the SpringExtension the
beforeTestMethod() and afterTestMethod() callbacks in the
TestExecutionListener API are not invoked if there was a previous
lifecycle failure.
Consequently, the reported drawbacks only exist when using Spring's
TestNG base support classes
This commit picks up where the previous commit left off by applying the
same hasApplicationContext() check in beforeTestMethod().
This commit also introduces unit and integration tests for both Jupiter
and TestNG support.
Closes gh-36782
Avoid using String#replaceAll when the pattern is not a regular
expression.
Using java.lang.String#replace(CharSequence, CharSequence) will
improve performance.
Closes gh-36678
Signed-off-by: shenjianeng <ishenjianeng@qq.com>
Prior to this commit, MIME types with parameter values that contain a
quoted pair would sometimes fail and parse an incomplete parameter
value.
This commit ensures that the quoted section of the parameter value is
correctly handled.
Fixes gh-36730
Prior to this commit, the `resolveUrlPath` implementation for the
`LiteWebJarsResourceResolver` would always delegate to the resource
chain once the versioned webjar folder has been resolved.
While this aligns with the `ResourceResolver` contract and the fact that
the resource chain does not resolve directories, here the WebJar locator
does support such use cases and we shouldn't get in the way here.
This commit falls back to the resolved versioned WebJar path if no
resource could be resolved and the path ends with "/".
Fixes gh-36726
StompBrokerRelayMessageHandler only set the host header in CONNECT
frames when virtualHost was explicitly configured. Per STOMP 1.2, the
host header is required on CONNECT frames.
Fall back to relayHost (the TCP connection target) when virtualHost is
not configured, ensuring the host header is always present in both
system session and client session CONNECT frames.
Closes gh-36673
Signed-off-by: cuitianhao <54015884+tianhaocui@users.noreply.github.com>
Prior to this commit, the `PartGenerator` would allow requesting
additional part tokens while in the `CreateFileState`. This is invalid
as any new token emitted would be rejected and would fail the entire
process.
This would only happen if the tmp file creation is slow enough for a new
token to be parsed and emitted.
This commit ensures that no new part token is requested while creating
the temporary file.
This change also fixes lifecycle issues and ensures that buffer
resources are cleaned in case of errors.
Fixes gh-36694
Prior to this commit, thread-local variables like Trace ID were not
automatically propagated into the Reactor Context when making requests
using Kotlin coroutine WebClient extensions like `awaitExchange`.
This commit updates `CoroutineContext.toReactorContext()` to capture
thread-local values via Micrometer Context Propagation when available,
ensuring observations and traces are properly reused.
Closes gh-36182
This commit fixes a regression introduced by gh-36449 for
nullable value class with an non-null value.
Closes gh-36665
Signed-off-by: Sigurd Gerke <sigurd.gerke@onedata.de>
Prior to this commit, there could be cache collisions in the
`CachingResourceResolver` because the cache key generation was
incomplete. This commit expands the cache key generation to avoid such
cases.
Fixes gh-36713
Prior to this commit, content based version strategies would remove all
instances of the version string in the request path when trying to
resolve the original resource with the chain.
This can cause issues in rare cases where there is a collision between
the content version and some other version string in the request path.
Because this strategy is based on the contents of the file itself, we
should only remove the last instance of the version string and then
attempt to resolve the original file.
Fixes gh-36698
As of gh-36692, Spring logs a WARN message when an unsafe resource
handling location is configured. This change now rejects entirely such
setups by failing before the application starts up.
Closes gh-36695
Prior to this commit, `ResourceHandlerUtils` would perform resource
location checks to ensure that the configured location is valid. This
commit also ensures that we log a WARN message if the application
chooses a well-known unsafe location like "classpath:" or the root
Servlet context for serving static resources.
Closes gh-36692
Prior to this commit, WebClientUtils.getRequestDescription()
created a new URI object on every invocation. Since the URI
constructor includes validation and parsing, which is already
performed by the parameter URI object, this was unnecessarily
expensive for a logging utility.
This commit reuses the original URI's string representation
to avoid redundant parsing.
This commit also strips userInfo, query, and fragment from the
log description even if URIs contain only userInfo or
fragment (without a query).
Closes gh-36641
Signed-off-by: 박동윤 (Park Dong-Yun) <ehddbs7458@gmail.com>
This commit reverts the changes made to WebDataBinder's doBind()
implementation in e4d03f6625 and instead implements the skipping logic
directly in checkFieldDefaults(), checkFieldMarkers(), and
adaptEmptyArrayIndices() by preemptively checking if the corresponding
field is allowed.
This commit also improves the Javadoc and adds missing tests.
Fixes gh-36625
In Spring Framework 7.0, we introduced support for using `Optional`
with the null-safe and Elvis operators in SpEL expressions; however,
such expressions were previously not compilable.
To address that, this commit introduces a new
insertOptionalUnwrapIfNecessary() method in CodeFlow which effectively
inserts byte code instructions for `myOptional.orElse(null)`, and the
Elvis, Indexer, MethodReference, and PropertyOrFieldReference
implementations have been modified to track the need to unwrap an
`Optional` in compiled mode and delegate to
insertOptionalUnwrapIfNecessary() accordingly.
See gh-20433
See gh-36331
Closes gh-36330
HttpMethod.valueOf() performs a case-sensitive lookup of predefined
HttpMethod constants. For example, valueOf("GET") resolves to
HttpMethod.GET, whereas valueOf("get") results in a newly created
HttpMethod instance.
Update the Javadoc to explicitly document this behavior.
See gh-36642
Closes gh-36652
Signed-off-by: angry-2k <edkev@kakao.com>
This commit moves the JSON specific code to
KotlinSerializationJsonDecoder, uses switchOnFirst operator to keep the
existing behavior and derives the list serializer from the element one.
Closes gh-36597
Prior to this commit, the implementation of HttpMethod.valueOf()
aligned with the semantics of Enum#valueOf() which requires an exact
match for the enum constant name.
However, since HttpMethod is no longer an enum, that restriction is no
longer necessary. Consequently, this commit revises the implementation
of valueOf() to perform a case-insensitive lookup for predefined
constants.
In other words, HttpMethod.valueOf("GET") and HttpMethod.valueOf("get")
now both resolve to HttpMethod.GET.
Closes gh-36518
The Spring TestContext Framework does not honor the
`spring.profiles.active` system property when determining
active profiles for a test class if @ActiveProfiles is
used.
This commit documents that behavior in the @ActiveProfiles
and DefaultActiveProfilesResolver Javadoc, as well as in
the reference manual. A SystemPropertyActiveProfilesResolver
example is also added showing how to allow
`spring.profiles.active` to override @ActiveProfiles.
See gh-36269
Closes gh-36600
Signed-off-by: Mohak Nagaraju <98132980+Mohak-Nagaraju@users.noreply.github.com>
Prior to this commit, fields that are not allowed for binding were
always skipped and would not be bound. But the field and default marker
support (with the "_" and "!" prefixes) would be still considered and
could trigger collection instantiation/autogrow.
While this does not cause unwanted binding, this allocates memory for no
reason. This commit revisits the binding algorithm to only consider
default and field marker support if the regular field is allowed.
Fixes gh-36625
Prior to this commit, SqlScriptsTestExecutionListener unwrapped data
sources wrapped in an InfrastructureProxy or a scoped proxy, but it did
not unwrap a data source wrapped in a TransactionAwareDataSourceProxy.
Consequently, the sameDataSource() check failed in the latter case,
preventing execution of @Sql scripts.
To address that, this commit revises sameDataSource() to unwrap a
TransactionAwareDataSourceProxy as well, analogous to the
implementations of setDataSource() in DataSourceTransactionManager,
JpaTransactionManager, and HibernateTransactionManager.
Closes gh-36611
Use defensive Date copies for sentDate to avoid shared mutable state.
Apply consistent handling in setSentDate, getSentDate, the copy constructor, and copyTo.
Add regression tests for mutation safety and copy isolation.
Closes gh-36626
Signed-off-by: Junseo Bae <ferrater1013@gmail.com>
Use `CollectionUtils::newLinkedHashSet` instead of `LinkedHashSet::new` to avoid resizing.
Closes gh-36618
Signed-off-by: Yanming Zhou <zhouyanming@gmail.com>
We currently have three implementations of MethodMetadata:
- StandardMethodMetadata (Java reflection)
- SimpleMethodMetadata (ASM)
- ClassFileMethodMetadata (ClassFile API)
The ASM and ClassFile variants return a string equivalent to
Class#getTypeName(); whereas, StandardMethodMetadata currently returns a
binary name using Class#getName() (for example, `[I` instead of `int[]`).
In order to align with the ASM and ClassFile variants and provide
consistent results for all MethodMetadata implementations, this commit
revises StandardMethodMetadata.getReturnTypeName() to use
Class#getTypeName().
Closes gh-36619
Prior to this commit, the `return` keyword was missing in
TypeMappedAnnotation's getClassLoader() implementation, which prevented
the ClassLoader of the Member (Method or Field) from being used.
This commit fixes that by adding the missing `return` keyword and adds
a test using a custom ClassLoader to verify the correct behavior.
Closes gh-36606
ProfilesParser.parseTokens() silently accepts unbalanced parentheses
in profile expressions such as "dev)" or "(dev", treating them as
valid. This can lead to unexpected behavior where malformed @Profile
annotations are silently interpreted instead of being rejected.
This commit tightens the validation in parseTokens() to reject:
- Unmatched closing parenthesis at the top level
- Unmatched opening parenthesis when tokens are exhausted
Also fixes an existing test that inadvertently relied on this lenient
behavior by using "spring&framework)" instead of "(spring&framework)".
Closes gh-36550
Signed-off-by: daguimu <daguimu.geek@gmail.com>
Prior to this commit, we invoked `Class.getName()` when building error
messages during annotation processing, resulting in exceptions like the
following which use binary names for nested types and arrays.
Attribute 'chars' in annotation
org.springframework.core.annotation.AnnotationUtilsTests$CharsContainer
should be compatible with [C but a [I value was returned
This commit switches to canonical names in error messages in annotation
processing, resulting in improved such errors messages such as the
following.
Attribute 'chars' in annotation
org.springframework.core.annotation.AnnotationUtilsTests.CharsContainer
should be compatible with char[] but a int[] value was returned
In addition, this commit introduces a new getCanonicalName(Class) method
in ClassUtils, which has effectively been extracted from the following
classes where this functionality was previously duplicated.
- AttributeMethods
- SynthesizedMergedAnnotationInvocationHandler
- TypeDescriptor
- DefaultRetryPolicy
- ReflectiveIndexAccessor
Closes gh-36607
Prior to this commit, ClassFileAnnotationDelegate created
MergedAnnotations from a HashSet, which resulted in a non-deterministic
iteration order and lost the original source declaration order of the
annotations.
To address that, this commit revises ClassFileAnnotationDelegate to
create MergedAnnotations from a List.
In addition, this commit updates all related tests to use the
containsExactly() assertion instead of containsExactlyInAnyOrder() to
ensure we consistently adhere to the "source declaration order"
requirement.
Closes gh-36598
Prior to this commit, we used ClassUtils.resolveClassName() in
TypeMappedAnnotation.adapt(...) which throws an IllegalStateException
or IllegalArgumentException if a type referenced by an annotation
attribute cannot be loaded. However, if such an error occurs while
using the JDK's reflection APIs, a TypeNotPresentException is thrown
instead.
In order to align with the standard behavior of the JDK, this commit
modifies TypeMappedAnnotation.adapt(...) to use ClassUtils.forName()
and throw a TypeNotPresentException in such scenarios.
This commit also makes similar changes in
MergedAnnotationReadingVisitor and ClassFileAnnotationDelegate.
Closes gh-36593
Spring Framework 5.2 introduced a regression in our annotation
processing support when the MergedAnnotations API was introduced.
Consequently, prior to this commit, our "annotation attributes as a Map
or AnnotationAttributes instance" support no longer stored exceptions
thrown while attempting to load a type referenced by an annotation
attribute. Instead, the exception was thrown immediately.
To address that, this commit revises our MergedAnnotation.asMap()
support so that it now tracks such exceptions in the map instead of
immediately throwing them. This allows map functionality such as
contains(attributeName), keySet(), etc. to continue to function
properly. In addition, the internal getRequiredAttribute() method in
AnnotationAttributes once again properly throws the original exception
wrapped in an IllegalArgumentException whenever a caller invokes one of
the convenience methods such as getClass() and getClassArray().
Note that this affects both asMap() variants as well as
asAnnotationAttributes().
In addition, this commit reverts the fix applied in 00fbd91cca since
it is no longer necessary.
See gh-36524
Closes gh-36586
Prior to this commit, AnnotationBeanNameGenerator failed when searching
for a convention-based bean name, if an annotation referenced a
non-existent class.
To address that, this commit introduces a try-catch block around each
invocation of MergedAnnotation.asAnnotationAttributes() and skips
processing of the current MergedAnnotation if an exception occurs,
which is likely due to a type referenced from an annotation attribute
not being present in the classpath.
See gh-31203
Closes gh-36524
Revise the BeanRegistrar Javadoc to document the two distinct usage
modes: @Configuration/@Import and programmatic GenericApplicationContext
setup.
Clarify that implementations are not Spring components (requiring a
no-arg constructor and no dependency injection), and detail the ordering
guarantees for each mode.
Add missing tests
Signed-off-by: Stéphane Nicoll <stephane.nicoll@broadcom.com>
Prior to this commit, the ClassFile variant for annotation and method
metadata would report incorrect metadata for:
* the method return type names in case of primitives and array types
* `toString` values for methods
* `equals` and `hashcode` information for methods
This commit expands the test suite and ensures that the ASM and
ClassFile variants are aligned.
Fixes gh-36577
Signed-off-by: Brian Clozel <brian.clozel@broadcom.com>
Return correct names for primitive and array types
Introduce resolveTypeName helper for ClassDesc handling
Add ClassFileMethodMetadataTests (java24Test)
Extend AbstractMethodMetadataTests with void return case
See gh-36577
Signed-off-by: Junseo Bae <ferrater1013@gmail.com>
GenericApplicationContext-registered BeanRegistrars are invoked after other programmatic bean definitions. Configuration-imported BeanRegistrars participate in configuration class order and in particular in Boot's auto-configuration ordering.
Closes gh-21497
Prior to this commit, all `with**Converter` methods in
`HttpMessageConverters` builders would only apply if the
`registerDefaults()` option is on. While the original intent is to allow
overrides for auto-detected defaults, this creates an unnecessary
discrepancy with `addCustomConverter` which is always effective.
Allowing sich registrations when defaults are off should not introduce
invalid states and only reflects the intent of the developer. This
commit now allows such cases.
Fixes gh-36579
Since commit 89391fd94c, the getClassAttributeWhenUnknownClass() methods
in SimpleAnnotationMetadataTests and DefaultAnnotationMetadataTests
have failed in Eclipse, since the JSR-305 JAR is always on the test
runtime classpath in Eclipse.
To address that, this commit introduces a FilteringClassLoader in both
test classes which mimics the test runtime behavior in the Gradle build.
See gh-36432
`RestTemplate` is deprecated, this commit amends the JavaDoc to mention
its scheduled removal for the next major version, Spring Framework 8.0.
See gh-36574
Prior to this commit, the `RestTestClient` MockMvc integration would
support transforming client requests into MockMvc requests.
`RestTestClient` can serialize `MultiValueMap` request bodies as
multipart requests. In this case, the `MockMvcClientHttpRequestFactory`
would only read the body as byte stream and would not turn this into a
proper `MockMultipartHttpServletRequestBuilder`.
This commit uses the new `MultipartHttpMessageConverter` to parse the
request payload as `MockPart` instances to be added to the MockMvc
requests.
Closes gh-35569
CacheAspectSupport currently contains a protected methodIdentification()
method which is not used internally within the framework, and it appears
that it was accidentally copied from TransactionAspectSupport when the
caching support was first introduced.
In light of that, this commit deprecates it for removal in 7.1.
Closes gh-36576
Prior to this commit, thread-local variables like Trace ID were not
automatically propagated into the Reactor Context when making requests
using Kotlin coroutine WebClient extensions like `awaitExchange`.
This commit updates `CoroutineContext.toReactorContext()` to capture
thread-local values via Micrometer Context Propagation when available,
ensuring observations and traces are properly reused.
Closes gh-36182
As announced in "the state of HTTP clients in Spring" blog post
(https://spring.io/blog/2025/09/30/the-state-of-http-clients-in-spring),
the deprecation timeline for `RestTemplate` was announced last November
and docs were updated accordingly.
This commit `@Deprecate` `RestTemplate` and related types for removal to
send a stronger signal to our community.
The actual removal is scheduled for Spring Framework 8.0 (not yet
scheduled).
Closes gh-36574
Now that `RestClient` offers a better alternative, this commit revisits
our integration tests to use `RestClient` instead of `RestTemplate`.
Closes gh-36573
Prior to this commit, `MockRestServiceServer` would provide
`createServer` shortcuts for `RestTemplate` and `RestGatewaySupport`.
Now that `RestClient` offers a modern client variant, we should provide
the same for `RestClient`.
Closes gh-36572
Prior to this commit, the `SockJsClient` would use the
`RestTemplateXhrTransport`. `RestClient` is a modern replacement for
RestTemplate and should be used instead.
This commit introduces the `RestClientXhrTransport` variant as an
immediate replacement.
Closes gh-36566
Prior to this commit, @MockitoBean and @MockitoSpyBean could be
declared on fields or at the type level (on test classes and test
interfaces), but not on constructor parameters. Consequently, a test
class could not use constructor injection for bean overrides.
To address that, this commit introduces support for @MockitoBean and
@MockitoSpyBean on constructor parameters in JUnit Jupiter test
classes. Specifically, the Bean Override infrastructure has been
overhauled to support constructor parameters as declaration sites and
injection points alongside fields, and the SpringExtension now
recognizes composed @BeanOverride annotations on constructor
parameters in supportsParameter() and resolves them properly in
resolveParameter(). Note, however, that this support has not been
introduced for @TestBean.
For example, the following which uses field injection:
@SpringJUnitConfig(TestConfig.class)
class BeanOverrideTests {
@MockitoBean
CustomService customService;
// tests...
}
Can now be rewritten to use constructor injection:
@SpringJUnitConfig(TestConfig.class)
class BeanOverrideTests {
private final CustomService customService;
BeanOverrideTests(@MockitoBean CustomService customService) {
this.customService = customService;
}
// tests...
}
With Kotlin this can be achieved even more succinctly via a compact
constructor declaration:
@SpringJUnitConfig(TestConfig::class)
class BeanOverrideTests(@MockitoBean val customService: CustomService) {
// tests...
}
Of course, if one is a fan of so-called "test records", that can also
be achieved succinctly with a Java record:
@SpringJUnitConfig(TestConfig.class)
record BeanOverrideTests(@MockitoBean CustomService customService) {
// tests...
}
Closes gh-36096
Prior to this commit, one could invoke
ResolvableType.forMethodParameter(MethodParameter.forParameter(parameter))
to create a ResolvableType for a Parameter; however, that's slightly
cumbersome.
To address that, this commit introduces ResolvableType.forParameter(),
analogous to existing convenience factory methods in ResolvableType.
Closes gh-36545
Since equivalent Assert.notNull() checks are already performed by
subsequent code (constructors and factory methods), there is no need
to perform the exact same assertion twice in such use cases.
Closes gh-36544
This commit adds integration tests and reference documentation
for multipart support in `RestClient` and `RestTestClient`.
Closes gh-35569
Closes gh-33263
Prior to this commit, the `FormHttpMessageConverter` would only support
`MultiValueMap` payloads for reading and writing. While this can be
useful when web forms contain multiple values under the same key, this
prevent developers from using a common `Map` type and factory methods
like `Map.of(...)`.
This commit relaxes constraints in `FormHttpMessageConverter` and
ensures that `Map` types are supported for reading and writing URL
encoded forms.
Note that when reading forms to a `Map`, only the first value for each
key will be considered and other values will be dropped if they exist.
Closes gh-36408
Prior to this commit, gh-36255 introduced the new
`MultipartHttpMessageConverter`, focusing on multipart message
conversion in a separate converter. The `FormHttpMessageConverter` did
conflate URL encoded forms and multipart messages in the same converter.
With the introduction of the new converter and related types in the same
package (with `Part`, `FormFieldPart` and `FilePart`), we can now
revisit this arrangement.
This commit restricts the `FormHttpMessageConverter` to URL encoded
forms only and as a result, changes its implementation to only consider
`MultiValueMap<String, String>` types for reading and writing HTTP
messages. Because type erasure, this converter is now a
`SmartHttpMessageConverter` to get better type information with
`ResolvableType`.
As a result, the `AllEncompassingFormHttpMessageConverter` is formally
deprecated and replaced by the `MultipartHttpMessageConverter`, by
setting part converters explicitly in its constructor.
Closes gh-36256
Prior to this commit, the `FormHttpMessageConverter` would write, but
not read, multipart HTTP messages. Reading multipart messages is
typicaly performed by Servlet containers with Spring's
`MultipartResolver` infrastructure.
This commit introduces a new `MultipartHttpMessageConverter` that copies
the existing feature for writing multipart messages, borrowed from
`FormHttpMessageConverter`. This also introduces a new `MultipartParser`
class that is an imperative port of the reactive variant, but keeping it
based on the `DataBuffer` abstraction. This will allow us to maintain
both side by side more easily.
This change also adds new `Part`, `FilePart` and `FormFieldPart` types
that will be used when converting multipart messages to
`MultiValueMap<String, Part>` maps.
Closes gh-36255
The `AbstractHttpMessageConverter#supportsRepeatableWrites`
contract is a protected method that message converters can override.
This method tells whether the current converter can write several
times the payload given as a parameter. This is mainly useful on the
client side, where we need to know if we can send the same HTTP
message again, after receiving an HTTP redirect status.
Because this method is protected, this limits our ability to call
it from a different package; this is needed for gh-33263.
This commit promotes this method to the main `HttpMessageConverter`
interface and deprecates the former.
Closes gh-36252
Prior to this commit, `SseServerResponse.send()` would flush the
output stream returned by `getBody()`. Since gh-36385,
`ServletServerHttpResponse` wraps this stream with a non-flushing
decorator to avoid performance issues with `HttpMessageConverter`
implementations that flush excessively. As a result, SSE events were
no longer flushed to the client.
This commit changes `send()` to call `outputMessage.flush()` instead
of `body.flush()`, which properly delegates to the servlet response
`flushBuffer()` and is not affected by the non-flushing wrapper.
Fixes gh-36537
The resolveDependency() utility method in ParameterResolutionDelegate
resolves a dependency using the name of the parameter as a fallback
qualifier. That suffices for most use cases; however, there are times
when a custom parameter name should be used instead.
For example, for our Bean Override support in the Spring TestContext
Framework, an annotation such as @MockitoBean("myBean") specifies an
explicit name that should be used instead of name of the annotated
parameter.
Furthermore, introducing support for custom parameter names will
greatly simplify the logic in SpringExtension that will be required to
implement #36096.
To address those issues, this commit introduces an overloaded variant
of resolveDependency() which accepts a custom parameter name.
Internally, a custom DependencyDescriptor has been implemented to
transparently support this use case.
See gh-36096
Closes gh-36534
Prior to this commit, BeanOverrideHandler contained a large amount of
logic solely related to search algorithms for finding handlers.
Consequently, BeanOverrideHandler took on more responsibility than it
ideally should. In addition, we will soon increase the complexity of
those search algorithms, and we will need to make another utility
method public for use outside the bean.override package.
To address those issues, this commit extracts the search utilities from
BeanOverrideHandler into a new BeanOverrideUtils class.
Closes gh-36533
Prior to this commit, `HttpMessageConverters` would consider the JAXB
message converters when building `HttpMessageConverters` instances.
We noticed that, on the server side, the Jakarta JAXB dependency is very
common on the classpath and often brought transitively. At runtime, this
converter can use significant CPU resources when checking the
`canRead`/`canWrite` methods. This can happen when content types aren't
strictly called out on controller endpoints.
This commit changes the auto-detection mechanism in
`HttpMessageConverters` to not consider the JAXB message converter for
server use cases.
For client use cases, we keep considering this converter as the runtime
cost there is lower.
Closes gh-36302
This commit links the Spring Framework Observability section in the
reference documentation to the Micrometer docs describing how
Observations are handled as metrics.
Closes gh-34994
Prior to this commit, the `DefaultRestClient` implementation would
look at the type of the returned value to decide whether the HTTP
response stream needs to be closed before returning.
As of gh-36380, this checks for `InputStream` and `InputStreamResource`
return types, effectively not considering `ResponseEntity<InputStream>`
and variants.
This commit ensures that `ResponseEntity` types are unwrapped before
checking for streaming types.
Fixes gh-36492
When the Accept-Language header is present but blank, defaultLocale
was ignored and fell back to Locale.getDefault() (JVM system locale).
A blank header represents the same intent as an absent header.
Closes gh-36513
Signed-off-by: elgun.shukurov <elgun.sukurov@kapitalbank.az>
Prior to this commit, the following warning was emitted in the build.
w: file:///<path>/spring-framework/framework-docs/src/main/kotlin/org/springframework/docs/core/aop/ataspectj/aopataspectjexample/ConcurrentOperationExecutor.kt:57:29 Unnecessary non-null assertion (!!) on a non-null receiver of type 'PessimisticLockingFailureException'.
Prior to this commit, the extension context scope used by the
SpringExtension defaulted to test-method scoped and could only be
changed on a per-class basis via the @SpringExtensionConfig
annotation. However, having to annotate each affected test class is
cumbersome for developers who wish to use test-class scoped extension
context semantics across their code base.
To address that, this commit introduces support for configuring the
global default extension context scope for the SpringExtension via
Spring properties or JUnit properties.
Specifically, this commit introduces a
`spring.test.extension.context.scope` property that can be set via the
SpringProperties mechanism or via a JUnit Platform configuration
parameter.
See gh-35697
Closes gh-36460
Prior to this commit, different resource resolvers would resolve
accepted codings from the HTTP request sent by the client. This would be
done with different implementations, which could lead to resolution
errors and desynchronizations.
This commit now introduced a new shared method in
`EncodedResourceResolver` (Servlet and Reactive) to perform a consisten
resolution.
Fixes gh-36507
- Avoid the use of assertThat(Arrays.equals(...))
- Convert assertThat(Boolean.FALSE).isEqualTo(x) to assertThat(x).isEqualTo(Boolean.FALSE)
- Convert assertThat(Boolean.TRUE).isEqualTo(x) to assertThat(x).isEqualTo(Boolean.TRUE)
- Convert assertThat(x.equals(y)).isTrue() to assertThat(x).isEqualTo(y)
- Convert assertThat(x.equals(y)).isFalse() to assertThat(x).isNotEqualTo(y)
- Remove unnecessary parentheses in assertThat() arguments
- Convert assertThat(x instanceof X).isFalse() to assertThat(x).isNotInstanceOf()
- Convert assertThat(x instanceof X).isTrue() to assertThat(x).isInstanceOf()
- Convert assertThat(!x).isTrue() to assertThat(x).isFalse()
- Inline conditions in assertThat() statements
Closes gh-36504
Although this commit also changes the visibility of some test methods
to package-private, the remainder of that task will be addressed in
conjunction with gh-36496.
Closes gh-36495
Updates the Content-Disposition header creation logic to use only
ISO-8859-1 characters for the fallback 'filename' parameter instead of
RFC 2047 encoded strings. Non-compatible characters are replaced with '_'.
This does not remove the ability to parse RFC 2047 encoded filenames.
Closes gh-36328
Signed-off-by: Tobias Fasching <tobias.fasching@outlook.com>
Prior to this commit, the `StandardWebSocketUpgradeStrategy` would get
the HTTP headers from the handshake request and store them in the
WebSocket session for the entire duration of the session.
As of gh-36334, Spring MVC manages HTTP directly with a native API
instead of copying them. This improves performance but also uncovered
this bug: we cannot keep a reference to HTTP headers once the HTTP
exchange is finished, because such resources can be recycled and reused.
This commit ensures that the handshake headers are copied into the
session info to keep them around for the entire duration of the session.
Without that, Tomcat will raise an `IllegalStateException` at runtime.
This was already done for WebFlux in SPR-17250, but the latest header
management changes in Framework uncovered this issue for the Standard
WebSocket container case.
Fixes gh-36486
Prior to this commit, Spring web frameworks were using the
"application/x-ndjson" media type for streaming JSON payloads delimited
with newlines.
The "application/jsonl" media type seems to gain popularity in the
broader ecosystem and could supersede NDJSON in the future. This commit
adds support for JSON Lines as an alternative.
Closes gh-36485
Introduces a general-purpose consumeContent method on Resource and EncodedResource with special behavior for multi-content resources. Regular getInputStream/getReader calls will expose the merged content of all same-named resources in the classpath.
Closes gh-36415
Prior to this commit, the `WebTestClient` could only accept non-nullable
types in its `expectBodyList<T>` Kotlin extension function.
This commit relaxes this requirements to allow for more assertions.
Fixes gh-36476
This commit ensures that `ParameterizedTypeReference<T>` can accept
nullable types. This is especially useful for Kotlin extension functions
and assertion contracts.
Fixes gh-36477
Since the Spring Framework uses American English spelling, this commit
updates Javadoc and the reference manual to ensure consistency in that
regard. However, there are two exceptions to this rule that arise due
to their use within a technical context.
- We use "cancelled/cancelling" instead of "canceled/canceling" in
numerous places (including error messages).
- We use "implementor" instead of "implementer".
Closes gh-36470
Prior to this commit, if a superclass or enclosing test class (such as
one annotated with @SpringBootTest or simply
@ExtendWith(SpringExtension.class)) was not annotated with
@ContextConfiguration (or @Import with @SpringBootTest), the
ApplicationContext loaded for a subclass or @Nested test class would
not use any default context configuration for the superclass or
enclosing test class.
Effectively, a default XML configuration file or static nested
@Configuration class for the superclass or enclosing test class was
not discovered by the AbstractTestContextBootstrapper when attempting
to build the MergedContextConfiguration (application context cache key).
To address that, this commit introduces a new
resolveDefaultContextConfigurationAttributes() method in
ContextLoaderUtils which is responsible for creating instances of
ContextConfigurationAttributes for all superclasses and enclosing
classes. This effectively enables AbstractTestContextBootstrapper to
delegate to the resolved SmartContextLoader to properly detect a
default XML configuration file or static nested @Configuration class
even if such classes are not annotated with @ContextConfiguration.
Closes gh-31456
This commit revises the resolveExplicitTestContextBootstrapper()
algorithm in BootstrapUtils to allow a local @BootstrapWith annotation
to override a meta-annotation within the same composed annotation.
Closes gh-35938
This commit apply extra checks to ScriptTemplateView resource handling
with ResourceHandlerUtils, consistently with what is done with static
resource handling.
Closes gh-36458
Restore both WebMVC and WebFlux variants that were deleted
by mistake in commit 4db2f8ea1b.
This commit also removes the empty resource loader path, as it is not
needed for the main WEB-INF/ use case that is typically configured
explicitly by the user, and not needed to pass the restored tests.
Closes gh-36456
Prior to this commit, the `ClassFile` based implementation of
`AnnotationMetadata` would rely on the `NestHost` class element to get
the enclosing class name for a nested class.
This approach works for bytecode emitted by Java11+, which aligns with
our Java17+ runtime policy. But there are cases where bytecode was not
emitted by a Java11+ compiler, such as Kotlin. In this case, the
`NestHost` class element is absent and we should instead use the
`InnerClasses` information to get it.
This commit makes use of `InnerClasses` to get the enclosing class name,
but still uses `NestHost` as a fallback for anonymous classes.
Fixes gh-36451
Uses ClassFileAnnotationMetadata name for actual AnnotationMetadata.
Moves JSR-305 dependency to compile-only for all spring-core tests.
Closes gh-36432
Prior to this commit, the `setMessageConverters` method would have
private visibility. But `initBodyConvertFunction`, which is `protected`,
relies on the message converters being set in the first place.
While this works with `RestTemplate` because this is done automatically,
the `RestClient` does offer a builder method to configure a
`ResponseErrorHandler` and this makes it impossible to configure
converters in this case.
This commit aligns the method visibility by making it protected.
Closes gh-36434
Prior to this commit, our implementation of Server Sent Events (SSE),
`SseEmitter` (MVC) and `ServerSentEvent` (WebFlux), would not guard
against invalid characters if the application mistakenly inserts such
characters in the `id` or `event` types.
Both implementations would also behave differently when it comes
to escaping comment multi-line events.
This commit ensures that both implementations handle multi-line comment
events and reject invalid characters in id/event types.
This commit also optimizes `String` concatenation and memory usage
when writing data.
Fixes gh-36440
This will:
1. Mathematical Distribution (Collision Reduction)
2. Pipelining and CPU Caching
3. Avoiding "Method Heavy" Expressions
See gh-36325
Signed-off-by: Agil <41694337+AgilAghamirzayev@users.noreply.github.com>
- Extract code examples to separate Java, Kotlin, and XML files
- Add Kotlin configuration sample alongside Java
- Change "Java Config" terminology to "Programmatic Configuration"
- Use include-code directive for better maintainability
See gh-36323
Signed-off-by: jisub-dev <kimjiseob1209@gmail.com>
The internal buildMergedContextConfiguration() method in
AbstractTestContextBootstrapper originally resolved the
ApplicationContextInitializer set only once. However, the changes made
in commit 2244461778 introduced a regression resulting in the
initializers being resolved twice: once for validation and once for
actually building the merged context configuration. In addition, the
resolution for validation does not honor the inheritInitializers flag
in ContextConfigurationAttributes.
To address these issues, buildMergedContextConfiguration() once again
resolves the context initializers once via
ApplicationContextInitializerUtils.resolveInitializerClasses().
See gh-18528
Closes gh-36430
The RequestHeaderOverrideWrapper did not deduplicate in keySet()
across underlying headers and overrides.
A similar change in size() even if it was working correctly,
to align with keySet and make it more efficient.
Closes gh-36418
This change ensures that maxFramePayloadLength from
WebsocketClientSpec is passed to ReactorNettyWebSocketSession.
Previously, the session used the default 64KB limit regardless
of client configuration, causing TooLongFrameException when
receiving larger frames from servers like Tomcat or Jetty.
See gh-36370
Signed-off-by: Artem Voronin <artem.voronin.dev@gmail.com>
Ideally, we should be able to reuse the ContextLoader that was resolved
in buildDefaultMergedContextConfiguration(); however, since we have
been informed that some implementations of resolveContextLoader()
mutate the state of the supplied ContextConfigurationAttributes to
detect default configuration classes, we need to invoke
resolveContextLoader() on the completeDefaultConfigAttributesList as
well in order not to break custom TestContextBootstrappers that exhibit
such side effects.
Closes gh-36390
Traditionally, AbstractResourceBasedMessageSource has only had a
setDefaultEncoding() method which accepts the name of the default
encoding character set. However, although we have recently made a
concerted effort within the framework to introduce support for
supplying a Charset instead of a character set's name, we had
overlooked this particular scenario.
In light of that, this commit introduces setDefaultCharset(Charset) and
getDefaultCharset() methods in AbstractResourceBasedMessageSource and
makes direct use of the available Charset in
ReloadableResourceBundleMessageSource and ResourceBundleMessageSource.
Furthermore, although technically a regression in behavior, invoking
setDefaultEncoding() on such MessageSource implementations with an
invalid character set name now results in an immediate
UnsupportedCharsetException at configuration time instead of a
NoSuchMessageException at runtime, which will help users to more easily
detect misconfiguration.
Closes gh-36413
This commit renames the
org.springframework.test.context.configuration.interfaces package to
org.springframework.test.context.config.interfaces in order to colocate
"config" related tests under the same package.
In Spring Framework 7.1, the TestContext Framework will reliably detect
all default context configuration within the type hierarchy or
enclosing class hierarchy (for @Nested test classes) above a given
test class; however, test suites may encounter failures once we make
that switch in behavior.
In order to help development teams prepare for the switch in 7.1, this
commit logs a warning similar to the following whenever default context
configuration is detected but currently ignored.
WARN - For test class [org.example.MyTests$NestedTests], the
following 'default' context configuration classes were detected but
are currently ignored: org.example.MyTests$Config. In Spring
Framework 7.1, these classes will no longer be ignored. Please update
your test configuration accordingly. For details, see:
https://docs.spring.io/spring-framework/reference/testing/testcontext-framework/ctx-management/default-config.html
See gh-31456
See gh-36392
Closes gh-36390
The methods to build a request in RestClientAdapter and WebClientAdapter
are now public to make it easier to create a custom adapter that wraps
the built-in ones and delegates for methods that can be the same.
Closes gh-36374
Prior to this commit, flush calls on the output stream returned by
`ServletServerHttpResponse#getBody` would be delegated to the Servlet
response output stream.
This can cause performance issues when `HttpMessageConverter` and other
web components write and flush multiple times to the response body.
Here, the Servlet container is in a better position to flush to the
network at the optimal time and buffer the response body until then.
This is particularly true for `HttpMessageConverters` when they flush
many times the output stream, sometimes due to the underlying codec
library. Instead of revisiting the entire message converter contract, we
are here ignoring flush calls to that output stream.
This change does not affect the client side, nor the
`ServletServerHttpResponse#flush` calls.
This commit also introduces a new Spring property
`"spring.http.response.flush.enabled"` that reverts this behavior change
if necessary.
Closes gh-36385
This commit adapts RuntimeHints to be compatible with v1.2.0 of the
GraalVM metadata format. The changes are as follows:
* Resources and resource bundles are now defined at the same level. This
is transparent to users.
* Serialization is no longer a top-level concept, but rather an
attribute of a type or proxy. The top-level concept has been deprecated
and the relevant methods have been added.
Closes gh-36379
Prior to this commit, a few implementations of the `HttpMessageConverter`
contract were inheriting from abstract classes. Those classes were
performing extra `OutputStream#flush` on the response body even though
this is the responsibility of the super class. Such abstract classes
do flush already, after delegating to the `writeInternal` method.
This commit ensures that we remove such extra calls as they tend to
waste resources for no added benefit.
Closes gh-36383
This commit updates the target type detection in
`ResourceHttpMessageConverter` to only support target types that are
relevant: `InputStreamResource` for streaming, and types assignable from
`ByteArrayResource` for non-streaming cases.
Closes gh-36368
The `AbstractMessageConverterMethodProcessor` is in charge of handling
controller method return values and to write those as HTTP response
messages. The content negotiation process is an important part.
The `MimeTypeUtils#sortBySpecificity` is in charge of sorting inbound
"Accept" media types by their specificity and reject them if the list
is too large, in order to protect the application from ddos attacks.
Prior to this commit, the content negotiation process would first get
the sorted "Accept" media types, the producible media types as
advertized by message converters - and collect the intersection of both
in a new list (also sorted by specificity). If the "Accept" list is
large enough (but under the limit), the list of compatible media types
could exceed that limit because duplicates could be introduced in that
list: several converters can produce the same content type.
This commit ensures that compatible media types are collected in a set
to avoid duplicates. Without that, exceeding the limit at this point
will throw an `InvalidMimeTypeException` that's not handled by the
processor and result in a server error.
Fixes gh-36300
This commit fixes the `configureMessageConverters` and
`configureMessageConvertersList` behavior.
`configureMessageConverters` was not executing consumers in their order
of registration (but in the reverse order).
`configureMessageConvertersList` was not executing multiple consumers
and was instead executing the first consumer multiple times.
This commit fixes both issues.
Fixes gh-36332
get method skips containsKey and instead checks if the enumeration
has elements, which should give the same behavior other than for
headers without values.
See gh-36334
- Optimize get method for request headers
- Update keySet methods to use custom extension of AbstractSet
- Drop use of native Tomcat headers, which could be an issue for
request and response wrappers that override header methods.
The performance of Servlet adapters should be similar for the
commonly used methods, and it should be possible to optimize
further for the future in HttpHeaders (e.g. by adding a
set alternative to put), and requesting Servlet API refinements.
Closes gh-36334
Prior to this commit, the reactive `MultipartParser` and `PartGenerator`
types were leaking memory at runtime in specific cases:
* many HTTP clients must send multipart requests to be parsed and close
the connection while uploading
* the `PartGenerator` must be configured to write file parts to
temporary files on disk
* concurrency, upload speed must be important to trigger cases where the
file system is not fast enough to consume incoming buffers
The `MultipartParser` parses and emits `BodyToken` to its sink
(here, the `PartGenerator`). By definition, Reactor's `FluxSink` when
created with `Flux.create(FluxSink)` will use a "buffer" strategy and
will queue emitted elements if they cannot be consumed.
Here, the cancellation signal does dispose internal states in the
`MultiPartParser` and `PartGenerator` but does not clear the internal
queue in `FluxSink`.
This commit ensures that an operation is registered to release buffers
on the discard event.
Fixes gh-36262
Prior to this commit, the `MediaType` and `MimeType` "copy" constructors
would not leverage the fact that the existing instance has been
validated already (types, subtype and parameters have been checked
already for errors) and the entire validation would be performed again.
This would also allocate map instances in the process.
This commit ensures that the already validated information is reused
directly and that we avoid unnessecary operations and allocations for
such constructors.
Closes gh-36318
Prior to this commit, the findAutowiredAnnotation() method in
AutowiredAnnotationBeanPostProcessor fully supported finding
@Autowired as a meta-annotation; however, the isRequired() method in
QualifierAnnotationAutowireCandidateResolver only found @Autowired as
a "directly present" annotation without any support for
meta-annotations.
For consistency and to avoid bugs, this commit revises
QualifierAnnotationAutowireCandidateResolver so that we always support
@Autowired as a meta-annotation.
Closes gh-36315
This commit revises AutowiredAnnotationBeanPostProcessor so that
determineRequiredStatus(MergedAnnotation<?>) only looks up the required
attribute once.
Closes gh-36314
The builder for `HttpMessageConverters` allows for auto-detection of
message converters on the classpath and their default registration when
`registerDefaults()` is called. Once called, there is no way to undo
this.
This commit adds a new `disableDefaults()` method to disable the default
registration and take full control over the list of message converters.
Closes gh-36303
Prior to this commit, AnnotationConfigUtils looked up @Lazy as a
meta-annotation at arbitrary depths (e.g., when used as a
meta-meta-annotation); however,
ContextAnnotationAutowireCandidateResolver only found @Lazy as a
"directly present" meta-annotation.
For consistency, this commit revises
ContextAnnotationAutowireCandidateResolver so that it also finds @Lazy
as a meta-annotation at arbitrary depths.
Closes gh-36306
Prior to this commit, ValidationAnnotationUtils looked up @Validated
as a meta-annotation at arbitrary depths (e.g., when used as a
meta-meta-annotation) in determineValidationGroups() but only as a
"directly present" meta-annotation in determineValidationHints().
For consistency, this commit revises determineValidationHints() so that
it finds @Validated as a meta-annotation at arbitrary depths as well.
Closes gh-36274
Prior to this commit, the `HttpEntityMethodProcessor` would create a new
`ServletServerHttpRequest` input message to parse the native Servlet
request, but would not reuse it for reading the request body using the
message converters.
In gh-32471, we applied a change that updates HTTP headers accordingly
when request parameters are read. But not reusing the input message
means that we are losing this update when instantiating the resulting
`HttpEntity`.
This commit ensures that `HttpEntityMethodProcessor` uses the input
message it just created when decoding the request body.
Fixes gh-36298
Prior to this commit, an attempt to restart the
StompBrokerRelayMessageHandler (SBRMH) resulted in an
IllegalStateException stating that the ReactorNettyTcpClient was still
in the process of "Shutting down." The reason is that a
ReactorNettyTcpClient cannot be restarted after it has been closed, and
that is by design.
To address that issue, this commit introduces an
`internallyManagedTcpClient` flag in SBRMH that is used to track
whether SBRMH is in charge of managing the TcpClient internally or if
the TcpClient was supplied by the user and is therefore managed
externally.
If SBRMH manages the TcpClient internally, isPauseable() returns
`true`, and the `tcpClient` field is set to null (in stopInternal())
when the handler is stopped. Consequently, a new internally managed
TcpClient will be created when the handler is restarted.
If the TcpClient is managed externally, the handler is not considered
to be "pauseable", and a reference to the externally managed TcpClient
is retained after the handler has been stopped. If the
ApplicationContext is subsequently restarted, the externally managed
TcpClient will be reused -- which may or may not work, depending on the
implementation of the TcpClient. Note, however, that this has always
been the behavior of SBRMH with regard to stop/start scenarios for
externally managed TcpClients.
Closes gh-36266
Prior to this commit, the "application/*+json" wildcard MIME type was
added to the list of supported MIME types in the JSON messaging
converter. This change wasn't fully reflected in the
`AbstractMessageConverter`, because only strict matching of type and
subtybe were considered.
This commit updates the `AbstractMessageConverter` to not only check the
type and subtype, but also check whether the supported MIME type
includes the one given as a parameter.
Fixes gh-36285
Includes fix for consistent PersistenceException in case of no unit found for name.
Includes proper tests for Local(Container)EntityManagerFactoryBean with scan setup.
Closes gh-36270
Closes gh-36271
This commit also updates the Javadoc for the SpringExtension and
@SpringExtensionConfig to point out that the SpringExtension always
uses a test-class scoped ExtensionContext if
@TestInstance(Lifecycle.PER_CLASS) semantics are in effect.
Closes gh-36240
This PR optimizes the performance of NamedParameterUtils#buildValueArray by deferring the call to findParameter(declaredParams, paramName, i).
Changes: In the original implementation, findParameter was called for every parameter in the loop, regardless of whether the paramValue retrieved from paramSource was already an instance of SqlParameterValue.
Since findParameter involves iterating through the declaredParams list (or performing lookups), skipping this call when paramValue instanceof SqlParameterValue is true reduces unnecessary CPU cycles and memory access, especially for queries with a large number of parameters or long declaredParams lists.
Signed-off-by: qwding <761945125@qq.com>
Prior to this commit, the `Netty4HeadersAdapter` `MultiValueMapi#remove`
implementation would return an empty list if no value was present. This
is not consistent with other implementations.
This change ensures that `null` is returned for those cases.
Fixes gh-36226
Use helpers from java.nio.file.Files for some methods in FileCopyUtils.
Additionally, add unit tests for the various file-related methods.
Signed-off-by: Patrick Strawderman <pstrawderman@netflix.com>
Prior to this commit, "new RetryTask<>" declarations whose
TaskCallbacks (implemented as lambda expressions) did not actually
throw an exception resulted in a compilation error in Eclipse:
"Unhandled exception type Exception".
This is due to the fact that RetryTask is declared with "E extends
Exception", and the Eclipse compiler therefore infers that the lambda
expression potentially throws a checked Exception.
To address that, this commit explicitly declares that the affected
lambda expressions throw unchecked RuntimeExceptions:
"new RetryTask<String, RuntimeException>"
Update `YamlProcessor` to allow any value to be inserted for
empty entries. This update will allow blank strings to be used
instead of `null` which better aligns with the way that
`.properties` files are loaded.
This update also allows allows the specified `emptyValue` to be
inserted instead of a blank String when the YAML contains `null`
or `~` values.
See gh-36197
See gh-19986
Signed-off-by: Phillip Webb <phil.webb@broadcom.com>
Add an additional `getFlattenedMap` method to `YamlProcessor` to allow
the resulting flattened map to include nulls.
This update will allow processor subclasses to tell the difference
between YAML that is defined with an empty object vs missing the key
entirely:
e.g.:
application:
name: test
optional: {}
vs
application:
name: test
optional: {}
Closes gh-36197
Signed-off-by: Phillip Webb <phil.webb@broadcom.com>
Prior to this commit, test methods in CaffeineReactiveCachingTests
were parameterized twice with the same configuration class.
See gh-31637
See gh-35833
In commit 9711db787e, we introduced support for disabling test
application context pausing via a Spring property or JVM system
property, as follows.
-Dspring.test.context.cache.pause=never
However, users may actually be interested in keeping the pausing
feature enabled if contexts are not paused unnecessarily.
To address that, this commit introduces a new
PauseMode.ON_CONTEXT_SWITCH enum constant which is now used by default
in the DefaultContextCache.
With this new pause mode, an unused application context will no longer
be paused immediately. Instead, an unused application context will be
paused lazily the first time a different context is retrieved from or
stored in the ContextCache. This effectively means that an unused
context will not be paused at all if the next test class uses the same
context.
Although ON_CONTEXT_SWITCH is the now the default pause mode, users
still have the option to enable context pausing for all usage scenarios
(not only context switches) by setting the Spring property or JVM
system property to ALWAYS (case insensitive) — for example:
-Dspring.test.context.cache.pause=always
This commit also introduces a dedicated "Context Pausing" section in
the reference manual.
See gh-36117
Closes gh-36044
Replace legacy Groovy DSL property assignment (space-separated) with
the standard assignment operator (=) in spring-aspects.gradle.
The legacy syntax is deprecated in Gradle 9 and will be removed in
Gradle 10. This change eliminates deprecation warnings during the
build and ensures future compatibility.
See gh-36132
Signed-off-by: Yejeong, Ham <dev@thelightway.kr>
This commit simplifies TransactionalOperator.executeAndAwait by removing
Optional. It is based on a proposal by @vlsi refined to handle properly
reactive transaction commits (see related commit
217b6e37a6).
Closes gh-36039
Implement EmbeddedValueResolverAware to resolve ${...} placeholders
in @HttpExchange URL attributes.
See gh-36126
Signed-off-by: Juhwan Lee <jhan0121@gmail.com>
Spring Framework 7.0 introduced support for pausing inactive
application contexts between test classes and restarting them once they
are needed again. If pausing and restarting are fast, this feature does
not have a negative impact on test suites.
However, if the pausing or restarting of certain Lifecycle components
in the application context is slow, that can have a negative impact on
the duration of the overall test suite.
In gh-36044, we hope to find a way to avoid unnecessarily pausing an
application context after a test class if the same context is used by
the next test class that is run. That should help reduce the risk of a
negative impact caused by the pause/restart feature; however, for
certain scenarios that may not be enough. In light of that, this commit
introduces a mechanism for completely disabling the pausing feature via
a Spring property or JVM system property, as follows.
-Dspring.test.context.cache.pause=never
See gh-35168
See gh-36044
Closes gh-36117
Ensure that the DefaultApiVersionInserter does not re-encode existing parts
of the input URI by using the 'encoded' flag in UriComponentsBuilder.
This prevents percent-encoded characters (like %20) from being incorrectly
double-encoded to %2520 during the version insertion process.
See gh-36097
Signed-off-by: Nabil Fawwaz Elqayyim <master@nabilfawwaz.com>
Prior to this commit, the following method in AbstractMessageSendingTemplate
simply ignored the supplied headers map.
convertAndSend(Object, Map<String, Object>, MessagePostProcessor)
Closes gh-36120
Prior to this commit, if the JmsClient was configured with a default
destination name (instead of a default Destination), invoking the
sendAndReceive() variant which accepts a map of headers resulted in an
exception stating that a default destination is required.
To address that, this commit overrides the
convertSendAndReceive(Object, Map<String, Object>, Class<T>, MessagePostProcessor)
method in JmsMessagingTemplate to add support for both a default
Destination and a default destination name.
Closes gh-36118
Instead of making it async and having a sync subinterface variant,
this restores ApiVersionResolver to be as it was with an async
subinterface variant.
ApiVersionStrategy, and the infrastructure invoking it, remains
async first, but also accommodates sync resolvers.
This should provide a better balance with backwards compatibility
while also accommodating async version resolution as the less
common scenario.
See gh-36084
Prior to this commit, the algorithm behind determineBasicProperties()
in PropertyDescriptorUtils did not reliably resolve the correct write
method when one candidate write method had a parameter type that was a
subtype of another candidate write method whose parameter type was an
exact match for the resolved read method's return type.
In other words, the algorithm always resolved the candidate write
method with the most specific parameter type (similar to covariant
return types) which is not necessarily the resolved read method's
return type.
To address that, this commit ensures that determineBasicProperties()
always selects an exact match for the write method whenever possible.
As an added bonus, determineBasicProperties() no longer invokes
BasicPropertyDescriptor.getWriteMethod(), which avoids triggering the
resolution algorithm multiple times (when multiple write method
candidates exist), resulting in lazy resolution of the write method the
first time client code invokes getWriteMethod().
Closes gh-36113
This commit introduces ContextClassRequestBodyAdvice which adds a
"contextClass" hint allowing to resolve generics for Optional,
HttpEntity or ServerSentEvent container types.
Closes gh-36111
This commit introduces tests for proper support for non-generic types
in PropertyDescriptorUtils.determineBasicProperties(), effectively to
test the status quo and serve as regression tests.
While an API version may be important for mapping in an ERROR dispatch,
it is more important to allow the original exception to be handled.
Closes gh-36058
Among HandlerMapping's some may not expect an API version. This is why
those that do must be careful not to raise API validation errors if
they don't match the request.
Closes gh-36059
Use lazy evaluation in SingleCharWildcardedPathElement to avoid
unnecessary Character.toLowerCase() calls.
Resolves performance TODO from 2017.
Closes gh-36095
Signed-off-by: Minkyu Park <rb6609@naver.com>
This commit adds a new `configureMessageConvertersList` method on the
builder to add/remove/move converters in the resulting list before they
are individually post-processed.
This allows to re-introduce a behavior that was missing with the new
contract: the ability to append a converter at the end of the list.
See gh-36083
Signed-off-by: hayden.rear <hayden.rear@gmail.com>
This commit updates the HttpComponents HttpClient to refer to the parsed
`HttpEntity` for the content-related HTTP response headers such as
encoding and body length.
Closes gh-36100
The Java sample for "Locale Interceptor" shows a
`urlHandlerMapping.setUrlMap(Map.of("...` line due the inability to
disable the code chomping Asciidoctor extension with the code include
one. It will be fixed by a subsequent commit or a bug fix in
https://github.com/spring-io/asciidoctor-extensions.
Closes gh-36099
As a follow up to commit 4b07edbaeb, this commit introduces tests for
PropertyDescriptorUtils.determineBasicProperties() using types with
bounded generics.
Note, however, that the following test effectively fails, since
PropertyDescriptorUtils.determineBasicProperties() does not match the
behavior of java.beans.Introspector. Consequently, this test method
currently changes the expected write method type conditionally.
resolvePropertiesWithUnresolvedGenericsInSubclassWithOverloadedSetter()
See gh-36019
Like what we did for `@EnableWebMvc`, we want to remove `@EnableWebFlux`
from typical code snippets extending WebFluxConfigurer to make them more
Spring Boot friendly.
Closes gh-36091
This commits udpates ConverterFactory#getConverter to accept both
nullable and non-null T in the Converter return value.
Flexible nullability at ConverterFactory type level would have been
ideal, but is not possible due to how Kotlin deals with Class<T> when
T is nullable.
See gh-36063
This commit also replaces Arch Unit packageInfoShouldBeNullMarked() rule
by either configuring requireExplicitNullMarking = false when the whole
module does not have JSpecify annotations, or explicit @NullUnmarked
when some have and some don't.
See gh-36054
Prior to this commit, the determineBasicProperties() method in
PropertyDescriptorUtils did not reliably resolve read/write methods in
type hierarchies with generics. This utility method is used by
SimpleBeanInfoFactory which is used by BeanUtils and BeanWrapperImpl.
Thus, failure to reliably resolve read/write JavaBeans methods resulted
in bugs in certain scenarios.
For example, BeanUtils.copyProperties() randomly failed to copy certain
properties if the write method for the property could not be resolved.
To address such issues, this commit revises the implementation of
PropertyDescriptorUtils as follows.
1) Read methods with covariant return types are now consistently
resolved correctly.
2) If multiple ambiguous write methods are discovered, the algorithm now
checks for an exact match against the resolved generic parameter type
as a fallback.
Closes gh-36019
This commit updates the `HttpHeaders` javadoc to better reflect that
`asSingleValueMap()`, `asMultiValueMap()`, and `toSingleValueMap()` all
return case-sentitive map implementations.
Closes gh-36070
In gh-35947, the `Converter` contract was refined to allow for nullable
return values. This created a mismatch with the `ConverterFactory`
contract.
This commit fixes this mismatch by allowing nullable return values in
`Converter` instances created by `ConverterFactory`.
Fixes gh-36063
Prior to this commit, the `StringHttpMessageConverter` would perform a
flush after writing the body, via `StreamUtils#copy`. This operation is
not needed as a flush is already performed by the abstract class.
Flush calls by HTTP message converters is being reconsidered altogether
in gh-35427, but we should first remove this extra operation.
Closes gh-36065
Prior to this commit, we found in gh-35953 that using the `WebTestClient`
the following way leaks data buffers:
```
var body = client.get().uri("download")
.exchange()
.expectStatus().isOk()
.returnResult()
.getResponseBodyContent();
```
Here, the test performs expectations on the response status and headers,
but not on the response body. The WiretapConnector already supports this
case by subscribing to the Flux response body in those cases and
accumulating the entire content as a single byte[].
Here, the `DataBuffer` instances are not decoded by any `Decoder` and
are not released. This results in a memory leak.
This commit ensures that the automatic subscription in
`WiretapConnector` also releases the buffers automatically as the DSL
does not allow at that point to go back to performing body expectations.
Fixes gh-36050
This commit improves TestCompiler to expose both errors and warnings
instead of an opaque message. When compilation fails, both errors and
warnings are displayed.
This is particularly useful when combined with the `-Werror` option
that turns the presence of a warning into an error.
Closes gh-36037
This includes MethodParameter resolving getParameterName() by default now.
initParameterNameDiscovery(null) can be used to suppress such resolution.
Closes gh-36024
Prior to this commit, the `RfcUriParser` would ignore URI fragments if
their length is < 2. This commit fixes the length check to allow for
single char fragments when parsing URIs.
Fixes gh-36029
Prior to this commit, the `JdkClientHttpRequest` would add all values
from `HttpHeaders` to the native request builder. This could cause
`NullPointerException` being thrown at runtime because the `HttpClient`
does not support that.
This commit replicates a fix that was applied to the
`SimpleClientHttpRequest`, turning null values into empty "".
Fixes gh-35996
Return the requested resource as ErrorResponse.getDetailMessageArguments,
making it usable with message customization and i18n.
See gh-35758
Signed-off-by: Samuel Gulliksson <samuel.gulliksson@gmail.com>
Prior to this commit, if an enclosing test class (such as one annotated
with @SpringBootTest or simply @ExtendWith(SpringExtension.class))
was not annotated with @ContextConfiguration (or @Import with
@SpringBootTest), the ApplicationContext loaded for a @Nested test
class would not use any default context configuration for the enclosing
test class.
Effectively, a default XML configuration file or static nested
@Configuration class for the enclosing test class was not discovered
by the AbstractTestContextBootstrapper when attempting to build the
MergedContextConfiguration (application context cache key).
To address that, this commit introduces a new
resolveDefaultContextConfigurationAttributes() method in
ContextLoaderUtils which is responsible for creating instances of
ContextConfigurationAttributes for all superclasses and enclosing
classes. This effectively enables AbstractTestContextBootstrapper to
delegate to the resolved SmartContextLoader to properly detect a
default XML configuration file or static nested @Configuration class
even if such classes are not annotated with @ContextConfiguration.
Closes gh-31456
The error message in such cases now indicates that the retry process
is being aborted preemptively due to pending sleep time.
For example:
Retry policy for operation 'myMethod' would exceed timeout (5 ms) due
to pending sleep time (10 ms); preemptively aborting execution
See gh-35963
To improve diagnostics, this commit logs a DEBUG message including the
RetryException thrown by RetryTemplate when it's used behind the scenes
for @Retryable method invocations.
Closes gh-35983
Specifically, this commit introduces:
- timeout and timeoutString attributes in @Retryable
- a default getTimeout() method in RetryPolicy
- a timeout() method in RetryPolicy.Builder
- an onRetryPolicyTimeout() callback in RetryListener
- support for checking exceeded timeouts in RetryTemplate (also used
for imperative method invocations with @Retryable)
- support for checking exceeded timeouts in reactive pipelines with
@Retryable
Closes gh-35963
Prior to this commit, the `JdkClientHttpRequestFactory` would support
decompressing gziped/deflate encoded response bodies but would fail if
the response has no body but has a "Content-Encoding" response header.
This happens as a response to HEAD requests.
This commit ensures that only responses with actual message bodies are
decompressed.
Fixes gh-35966
This commit revises the type-level nullability declaration in
ConvertingComparator in order to adapt to recent nullability changes in
Converter.
This commit also revises the workaround in commit 53d9ba879d.
See gh-35947
As of Micrometer Tracing 1.6.0, the `Propagator.Getter` interface
adds a new `getAll` method with a default implementation return a
singleton collection.
This commit adds the missing implementation override in both Servlet and
Reactor web server contexts.
Fixes gh-35965
Add warnings to the class-level Javadoc for MergedAnnotations,
AnnotatedTypeMetadata, AnnotationMetadata, and MethodMetadata to point
out that annotations may be ignored if their attributes reference types
that are not present in the classpath.
Closes gh-35959
Allow defining converters that return non-null values by
leveraging flexible generic type level nullability in
org.springframework.core.convert.converter.Converter.
Closes gh-35947
In contrast to the previous commit, a warning similar to the following
is now logged in such cases.
WARN o.s.c.a.MergedAnnotation -
Failed to introspect meta-annotation @MyAnnotation on class
example.Config: java.lang.TypeNotPresentException:
Type example.OptionalDependency not present
See gh-35927
Prior to this commit, if a meta-annotation could not be loaded because
its attributes referenced types not present in the classpath, the
meta-annotation was silently ignored.
To improve diagnostics for such use cases, this commit introduces WARN
support in IntrospectionFailureLogger and revises AttributeMethods.canLoad()
to log a warning if a meta-annotation is ignored due to an exception
thrown while attempting to load its attributes.
For example, a warning similar to the following is now logged in such
cases.
WARN o.s.c.a.MergedAnnotation -
Failed to introspect meta-annotation @example.MyAnnotation on class
example.Config: java.lang.TypeNotPresentException:
Type example.OptionalDependency not present
This commit also improves log messages in AnnotationTypeMappings.
Closes gh-35927
With this commit, we now include snapshots for main (which currently
correlates to 7.0.x), 6.2.x, and 7.0.x to 9.*.x.
Closes gh-35923
(cherry picked from commit 305a512a55)
AbstractKotlinSerializationHttpMessageConverter#writeInternal is able to
resolve the ResolvableType from the Object parameter when the provided
one via the ResolvableType parameter is not resolvable, but
AbstractKotlinSerializationHttpMessageConverter#canWrite lacks of
such capability.
This commit refines
AbstractKotlinSerializationHttpMessageConverter#canWrite to resolve the
ResolvableType from the Class<?> parameter when the provided one via the
ResolvableType parameter is not resolvable.
Closes gh-35920
Since its inception, instantiating an `HttpEntity` makes its
`HttpHeaders` read-only. While immutability is an interesting design
principle, here we shouldn't enforce this.
For example, developers can expect to instantiate a `ResponseEntity`
and still mutate its headers.
Closes gh-35888
Includes alignment for direct Optional injection points, consistently registering an autowiredBeanNames entry for an Optional as well as a non-Optional injection result.
Closes gh-35373
Closes gh-35919
Prior to this commit, `RestTestClient` tests could only perform
expectations on the response without consuming the body. In this case,
the client could leak HTTP connections with the underlying HTTP library
because the response was not entirely read.
This commit ensures that the response is always fully drained before
performing expectations. The client is configured to buffer the response
content, so further body expectations are always possible.
Fixes gh-35784
Extending AbstractSmartHttpMessageConverter typically requires to
override both Class and ResolvableType variants of canRead. This was not
intended as SmartHttpMessageConverter interface has default methods
doing the conversion from Class parameters to ResolvableType ones, but
AbstractHttpMessageConverter overrides it.
This commit changes AbstractSmartHttpMessageConverter canRead/canWrite
overrides from ResolvableType to Class ones that delegate to the
ResolvableType variants. It also refines
AbstractJacksonHttpMessageConverter accordingly.
Closes gh-35916
The UserTransaction read-only semantics are still in discussion. If they turn out to be stricter than Spring's read-only hint, we should only apply them when configured with an explicit enforceReadOnly=true flag at the Spring JtaTransactionManager level (similar to the same-named flag in DataSourceTransactionManager).
See gh-35915
See gh-35633
The RuntimeBeanReference(name, type) constructor was introduced in 7.0;
however, BeanDefinitionPropertyValueCodeGeneratorDelegates in our AOT
infrastructure was not updated to support the new constructor.
This commit revises BeanDefinitionPropertyValueCodeGeneratorDelegates
to ensure that AOT generated code for a RuntimeBeanReference uses the
RuntimeBeanReference(name, type) constructor, thereby retaining the
originally configured bean name.
See gh-35101
Closes gh-35913
For defensiveness against a singletonInstance/initialized visibility mismatch, we accept the locking overhead for pre-initialized null values (where we need the initialized field) in favor of a defensive fast path for non-null values (where we only need the singletonInstance field).
Closes gh-35905
This commit refines BindingReflectionHintsRegistrar with additional
dynamic hints for application-defined types, main core Java conversion
ones being already covered by ObjectToObjectConverterRuntimeHints.
Closes gh-35847
This commit revises the Integration Testing chapter to reference the
"Spring Framework Artifacts" wiki page instead of the nonexistent
"Dependency Management" section of the reference manual.
Closes gh-35890
Otherwise some header values are changed from "GMT" to "Z" and
some tests are broken. We don't want to change the current
runtime behavior, so this commit reverts the related change to
keep using ZoneId.of("GMT") in HttpHeaders.
Closes gh-35861
An annotation-specified proxyTargetClass attribute must only be applied when true, otherwise we need to participate in global defaulting.
Closes gh-35863
ServerSentEvent and String checks, removed from
KotlinSerializationSupport in Spring Framework 7.0, are reintroduced by
this commit at the right level (KotlinSerializationSupport for
ServerSentEvent and KotlinSerializationString(Decoder|Encoder) for
String).
Closes gh-35885
This commit fixes ServerSentEvent handling with Jackson encoder
when no Accept header is specified.
It also moves the String checks to the JSON codec level, as they do not
make sense for binary formats.
Closes gh-35872
This commit aligns RestOperationsExtensions.kt nullability with the
Java APIs one, like what has been done in gh-35846 for JdbcOperations.
Closes gh-35852
This commit updates JdbcOperationsExtensions.kt to:
- Properly use the spread operator for invoking Java methods with
a varargs parameter
- Align JdbcOperationsExtensions return values nullability
with the Java API (breaking change)
- Use varargs where Java counterpart does (breaking change, undo some
changes from gh-34668)
- Use nullable args instead of non-nullable ones
Closes gh-35846
If the RestClient was built with default message converters, then
in mutate, the saved builder also has 0 converters, and adding a
interferes with default registrations.
We need to check if there are no converters at all, and if so
use the default registrations.
See gh-35793
Read the respective fields only once in the values(), entrySet(), and
keySet() methods.
Closes gh-35822
Signed-off-by: Patrick Strawderman <pstrawderman@netflix.com>
The Spliterators returned by values, entrySet, and keySet incorrectly
reported the SIZED characteristic, instead of CONCURRENT. This could
lead to bugs when the map is concurrently modified during a stream
operation.
For keySet and values, the incorrect characteristics are inherited from
AbstractMap, so to rectify that the respective methods are overridden,
and custom collections are provided that report the correct Spliterator
characteristics.
Closes gh-35817
Signed-off-by: Patrick Strawderman <pstrawderman@netflix.com>
Since getApplicationContext() was originally not intended to be part of
the public API, its Javadoc is intentionally sparse. However, since it
is actually a public API used by third parties, this commit improves the
documentation for getApplicationContext() by pointing out that invoking
the method actually results in the context being eagerly loaded, which
may not be desired.
This commit also updates the Javadoc for supportsParameter() along the
same lines.
Closes gh-35764
This commit adds an integration test for `WebClient`, specifically
testing that a failure happening while pulishing the request body is
reported on the main reactive pipeline.
See gh-35678
Prior to this commit, `WebClientResponseException` would only support
the deprecated "unprocessable entity" status.
This commit adds the missing support for "unprocessable content" when
creating exceptions with `WebClientResponseException#create`.
Fixes gh-35802
Prior to this commit (and despite the changes made in commit
4593f877dd), WebSocketHttpHeaders was not compatible with the
HttpHeaders(HttpHeaders) constructor or the copyOf(HttpHeaders) and
readOnlyHttpHeaders(HttpHeaders) factory methods.
To address that, this commit revises the implementation of
WebSocketHttpHeaders so that it only extends HttpHeaders, analogous to
ReadOnlyHttpHeaders. In other words, WebSocketHttpHeaders no longer
stores or delegates to a local HttpHeaders instance.
Closes gh-35792
Prior to this commit, `HttpMessageConverters` would assert that the
given converter in `withXmlConverter` has a media type that is equal to
"application/xml" in its list of supported converters.
This approach would not work if the given converter supports
"application/xml;charset=UTF-8" because of the strict equal check being
performed.
This commit ensures that we only consider the type and subtype of the
considered media types when comparing, removing the parameters from the
picture.
Fixes gh-35801
Since HttpHeaders no longer implements MultiValueMap (see gh-33913),
a few interoperability issues have arisen between HttpHeaders and
WebSocketHttpHeaders.
To address those issues, this commit:
- Revises addAll(HttpHeaders), putAll(HttpHeaders), and putAll(Map) in
HttpHeaders so that they no longer operate on the HttpHeaders.headers
field.
- Overrides addAll(String, List), asSingleValueMap(), and
asMultiValueMap() in WebSocketHttpHeaders.
- Deletes putAll(HttpHeaders), putAll(Map), and forEach(BiConsumer) in
WebSocketHttpHeaders, since they do not need to be overridden.
This commit also removes unnecessarily overridden Javadoc in
WebSocketHttpHeaders and revises the implementation of several methods
in HttpHeaders so that they delegate to key methods such as get()
instead of directly accessing the HttpHeaders.headers field.
See gh-33913
Closes gh-35792
Consistently allow subtypes of ServerResponse to be returned for any
provided HandlerFunction and HandlerFilterFunction. Both allow use of
subtypes such as EntityServerResponse and RenderingResponse, and
in the end we support any ServerResponse.
Closes gh-35791
This commit picks up where commit a0baeae9cf left off.
Specifically, in order to align with the behavior of
AbstractMockHttpServletRequestBuilder, HtmlUnitRequestBuilder no longer
sets the local port in the MockHttpServletRequest.
See gh-35709
Prior to this commit, the `ReactorClientHttpRequestFactory` and the
`ReactorClientHttpRequest` would use the `Executor` from the current
event loop for performing write operations.
Depending on I/O demand, this work could be blocked and would result in
blocked Netty event loop executors and the HTTP client hanging.
This commit ensures that the client uses a separate Executor for such
operations. If the application does not provide one on the request
factory, a `Schedulers#boundedElastic` instance will be used.
Fixes gh-34707
Prior to this commit, Spring Framework's JSP form tags supported the
response encoding in most places; however, <form:select> and
<form:options> still did not support the response character encoding.
To address that, this commit updates SelectTag, OptionsTag, and
OptionWriter to provide support for response character encoding in the
`select` and `options` JSP form tags.
See gh-33023
Closes gh-35783
This commit adds a new withKotlinSerializationCborConverter
method to HttpMessageConverters and updates DefaultHttpMessageConverters
to put JSON and CBOR Kotlin Serialization converters before
their Jackson/GSON/JSONB counterparts with their new default
behavior that only handles classes with `@Serializable` at
type or generics level.
When there is no alternative converter for the same mime type,
Kotlin Serialization converters handle all supported cases.
Closes gh-35761
This commit updates Kotlin serialization converters to perform
an additional check invoking
KotlinDetector#hasSerializableAnnotation to decide if the
related type should be processed or not.
The goal is to prevent in the default arrangement conflicts
between general purpose converters like Jackson and
Kotlin serialization when both are used.
New constructors allowing to specify a custom predicate
are also introduced.
See gh-35761
This commit updates BaseDefaultCodecs by adding Kotlin
Serialization codecs before their Jackson/GSON counterparts
with their new default behavior that only handles classes with
`@Serializable` at type or generics level.
When there is no alternative codec for the same mime type,
Kotlin Serialization codecs handle all supported cases.
This commit also adds missing Jackson CBOR codecs, and moves both
CBOR and Protobuf codecs to a lower priority, as they are less
commonly used than JSON ones, with the same ordering used on
Spring MVC side.
See gh-35761
Closes gh-35787
This commit updates Kotlin serialization codecs to perform
an additional check invoking
KotlinDetector#hasSerializableAnnotation to decide if the
related type should be processed or not.
The goal is to prevent in the default arrangement conflicts
between general purpose codecs like Jackson and
Kotlin serialization when both are used.
New constructors allowing to specify a custom predicate
are also introduced.
See gh-35761
This commit introduces a KotlinDetector#hasSerializableAnnotation
utility method designed to detect types annotated with
`@Serializable` at type or generics level.
See gh-35761
Prior to this commit, the maximum number of retry attempts was
configured via @Retryable(maxAttempts = ...),
RetryPolicy.withMaxAttempts(), and RetryPolicy.Builder.maxAttempts().
However, this led to confusion for developers who were unsure if
"max attempts" referred to the "total attempts" (i.e., initial attempt
plus retry attempts) or only the "retry attempts".
To improve the programming model, this commit renames maxAttempts to
maxRetries in @Retryable and RetryPolicy.Builder and renames
RetryPolicy.withMaxAttempts() to RetryPolicy.withMaxRetries(). In
addition, this commit updates the documentation to consistently point
out that total attempts = 1 initial attempt + maxRetries attempts.
Closes gh-35772
This commit ensures that the JAR verification task runs on JDK 25 as
this feature has been introduced in https://bugs.openjdk.org/browse/JDK-8355940
Fixes gh-35777
See gh-35773
This commit ensures that both `VirtualThreadDelegate` implementations
expose the same public API. If not, JAR verification fails with the
following message:
```
jar --validate --file spring-core-6.2.13-SNAPSHOT.jar
entry: META-INF/versions/21/org/springframework/core/task/VirtualThreadDelegate.class, contains a class with different api from earlier version
```
Fixes gh-35773
Prior to this commit, HtmlUnitRequestBuilder set the server port in the
MockHttpServletRequest to -1 if the URL did not contain an explicit
port. However, that can lead to errors in consumers of the request that
do not expect an invalid port number.
In addition, HtmlUnitRequestBuilder always set the remote port in the
MockHttpServletRequest to the value of the server port, which does not
make sense, since the remote port of the client has nothing to do with
the port on the server.
To address those issues, this commit revises HtmlUnitRequestBuilder so
that it:
- Does not set the server and local ports if the explicit or derived
default value is -1.
- Consistently sets the server and local ports to the same valid value.
- Does not set the remote port.
Closes gh-35709
Prior to this commit, gh-35213 allowed wildcard path elments at the
start of path patterns. This came with an additional constraint that
rejected such patterns if the pattern segment following the wildcard one
was not a literal:
* `/**/{name}` was rejected
* `/**/something/{name}` was accepted
The motivation here was to make the performance impact of wildard
patterns as small as possible at runtime.
This commit relaxes this constraint because `/**/*.js` patterns are very
popular in the security space for request matchers.
Closes gh-35686
This commit improves the reference document to better reflect the
different between `*` or `{name}` on one side, and `**` or `{*path}` on
the other.
The former patterns only consider a single path segment and its content,
while the latter variants consider zero or more path segments. This
explains why `/test/{*path}` can match `/test`.
Closes gh-35727
Although @PersistenceContext and @PersistenceUnit are still not
supported in tests running in AOT mode, as of Spring Framework 7.0,
developers can inject an EntityManager or EntityManagerFactory into
tests using @Autowired instead of @PersistenceContext and
@PersistenceUnit, respectively.
See commit 096303c477
See gh-33414
Closes gh-31442
The JsonConverterDelegate interface replaces usages of
HttpMessageContentConverter to provides the flexibility to use either
message converters or WebFlux codecs.
HttpMessageContentConverter is deprecated, and replaced with a package
private copy (DefaultJsonConverterDelegate) in the
org.springframework.test.json package that is accessible through
a static method on JsonConverterDelegate.
See gh-35737
Prior to this commit, the `MappingMediaTypeFileExtensionResolver` would
resolve file extensions for a given media type by using a direct lookup
using the given media type provided by the request.
If the request contains a quality parameter like
"application/json;q=0.9", this would not resolve configured file
extensions for this media type.
While other media type parameters can be meaningful, the quality
parameter should not be used for lookups. This commit ensures that the
quality parameter is dropped before performing lookups.
Fixes gh-35754
Prior to this commit, an attempt to use @MockitoSpyBean to spy on a
scoped proxy configured with
@Scope(proxyMode = ScopedProxyMode.TARGET_CLASS) resulted in an
exception thrown by Mockito when the spy was stubbed. The exception
message stated "Failed to unwrap proxied object" but did not provide
any further insight or context for the user.
The reason is that ScopedProxyFactoryBean is used to create such a
scoped proxy, which uses a SimpleBeanTargetSource, which is not a
static TargetSource. Consequently,
SpringMockResolver.getUltimateTargetObject(Object) is not able to
unwrap the proxy.
In order to improve diagnostics for users, this commit eagerly detects
an attempt to spy on a scoped proxy and throws an exception with a
meaningful message. The following is an example, trimmed stack trace
from the test suite.
org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'myScopedProxy': Post-processing of
FactoryBean's singleton object failed
...
Caused by: java.lang.IllegalStateException:
@MockitoSpyBean cannot be applied to bean 'myScopedProxy', because
it is a Spring AOP proxy with a non-static TargetSource. Perhaps you
have attempted to spy on a scoped proxy, which is not supported.
at ...MockitoSpyBeanOverrideHandler.createSpy(MockitoSpyBeanOverrideHandler.java:78)
Closes gh-35722
Prior to this commit, the `HttpComponentsClientHttpRequestFactory` would
set the connection timeout on the request configuration. This has been
deprecated by the client itself and this value should be set while
creating the client on the connection manager itself.
This commit deprecates this method, as there is no way for the factory
to set this value anymore.
Closes gh-35748
Prior to this commit, `HttpMessageConverters` would consider the Kotlin
Serialization JSON converter as an alternative to the Jackson variant.
As seen in related issues, this converter is more commonly used for
annotated classes specifically and applications often rely on Jackson
acting as a fallback for types not supported by Kotlin Serialization.
This commit enables applications to configure such a converter on
`HttpMessageConverters` and order it ahead of of the JSON one.
Closes gh-35733
This commit adds AOT support for discovering @Nested test classes
within a @ClassTemplate test class, which includes
@ParameterizedClass test classes.
Closes gh-35744
Switching from @PersistenceContext to @Autowired for dependency
injection in tests allows such tests to participate in AOT processing.
Note, however, that we still have TestNG-based tests that use
@PersistenceContext — for example, AbstractEjbTxDaoTestNGTests.
See gh-29122
See gh-31442
See gh-33414
Replace obsolete Concourse pipeline reference with GitHub Actions.
The Concourse link returns 404.
See gh-35746
Signed-off-by: Moad ELFATIHI <elfatihi.moad@gmail.com>
The MockMvcClientHttpRequestFactoryTests variant for RestTestClient was
copied from MockMvcClientHttpRequestFactoryTests which actually uses
MockMvcClientHttpRequestFactory. In addition,
MockMvcClientHttpRequestFactoryTests unnecessarily used the
SpringExtension.
This commit therefore renames the class to MockMvcRestTestClientTests
and removes the use of the SpringExtension.
See gh-29122
This commit upgrades our test suite to use JUnit 6.0.1 and removes the
systemProperty("junit.platform.discovery.issue.severity.critical", "WARNING")
configuration from spring-test.gradle, so that all discovery issues will
fail the build for the spring-test module as well.
In addition, this commit prevents potential AOT test scanning failures
for JUnit 4 tests by setting the
"junit.vintage.discovery.issue.reporting.enabled" configuration
parameter to "false" in TestClassScanner.
See https://github.com/junit-team/junit-framework/issues/5030
Closes gh-35740
When JAR manifest Class-Path entries contain absolute paths (as Gradle
creates on Windows for long classpaths), PathMatchingResourcePatternResolver
incorrectly rejected them.
Fixes#35730
Signed-off-by: Artur Signell <artur@vaadin.com>
Prior to this commit, the `HttpMessageConverters` builder API had
methods like "jsonMessageConverter" for configuring a specific converter
for JSON support. This converter would be always configured at a given
position, even if default converters registration is not requested.
On the other hand, `customMessageConverter` would add any converter
ahead of the list, in all cases. This difference was not conveyed as it
should by the API.
This commit makes the following changes:
* builder methods are renamed to `withJsonConverter` and variants, to
better convey the fact that those are replacing the default converter
for a given format.
* `customMessageConverter` is renamed to `addCustomConverter` to better
reflect the additive aspect.
* the JavaDoc has been updated accordingly
* `withJsonConverter` and others are now only effective if the default
registration of auto-detected converters is requested. This better
aligns with the behavior in the reactive codecs configuration
Closes gh-35704
When concurrency limiting is enabled via setConcurrencyLimit() and
thread creation fails in doExecute() (e.g., OutOfMemoryError from
Thread.start()), the concurrency permit acquired by beforeAccess()
is never released because TaskTrackingRunnable.run() never executes.
This causes the concurrency count to permanently remain at the limit,
causing all subsequent task submissions to block forever in
ConcurrencyThrottleSupport.onLimitReached().
Root cause:
- beforeAccess() increments concurrencyCount
- doExecute() throws Error before thread starts
- TaskTrackingRunnable.run() never executes
- afterAccess() in finally block never called
- Concurrency permit permanently leaked
Solution:
Wrap doExecute() in try-catch block in the concurrency throttle path
and call afterAccess() in catch block to ensure permit is always
released, even when thread creation fails.
The fix only applies to the concurrency throttle path. The
activeThreads-only path does not need fixing because it never calls
beforeAccess(), so there is no permit to leak.
Test approach:
The test simulates thread creation failure and verifies that a
subsequent execution does not deadlock. The first execution should
fail with some exception (type doesn't matter), and the second
execution should complete within timeout if the permit was properly
released.
Signed-off-by: Park Juhyeong <wngud5957@naver.com>
Previously, SingletonSupplier stored "null" in singletonInstance when
the supplied instance was "null". On subsequent get() calls, this was
treated as "uninitialized" and triggered another attempt to obtain an
instance from the Supplier.
This commit ensures that a "null" returned from the instanceSupplier or
defaultSupplier is handled correctly, so that subsequent calls to get()
return "null" consistently instead of repeatedly invoking the Supplier.
Closes gh-35380
Signed-off-by: Dmytro Nosan <dimanosan@gmail.com>
As of Spring Framework 6.2.13, we support JUnit Jupiter 5.12's
ExtensionContextScope.TEST_METHOD behavior in the SpringExtension and
the BeanOverrideTestExecutionListener; however, users can only benefit
from that if they explicitly set the following configuration parameter
for their entire test suite, which may have adverse effects on other
third-party JUnit Jupiter extensions.
junit.jupiter.extensions.testinstantiation.extensioncontextscope.default=test_method
For Spring Framework 7.0, in order to support dependency injection into
test class constructors and fields in @Nested test class hierarchies
from the same ApplicationContext that is already used to perform
dependency injection into lifecycle and test methods (@BeforeEach,
@AfterEach, @Test, etc.), we have decided to configure the
SpringExtension to use ExtensionContextScope.TEST_METHOD by default. In
addition, we have decided to provide a mechanism for users to switch
back to the legacy "test-class scoped ExtensionContext" behavior in
case third-party TestExecutionListener implementations are not yet
compatible with test-method scoped ExtensionContext and TestContext
semantics.
This commit achieves the above goals as follows.
- A new @SpringExtensionConfig annotation has been introduced, which
allows developers to configure the effective ExtensionContext scope
used by the SpringExtension.
- The SpringExtension now overrides
getTestInstantiationExtensionContextScope() to return
ExtensionContextScope.TEST_METHOD.
- The postProcessTestInstance() and resolveParameter() methods in the
SpringExtension now find the properly scoped ExtensionContext for the
supplied test class, based on whether the @Nested test class
hierarchy is annotated with
@SpringExtensionConfig(useTestClassScopedExtensionContext = true).
See gh-35680
See gh-35716
Closes gh-35697
Previous commit 81ea35c726 in main for 7.0
should have been applied in 6.2.x first for 6.2.1.
This commit applies the changes in 6.2.x as intended,
effective as of 6.2.13.
Closes gh-33974
Although gh-35680 introduced support for JUnit Jupiter's TEST_METHOD
ExtensionContextScope in the SpringExtension and
BeanOverrideTestExecutionListener, those were internal changes that are
not directly visible by TestExecutionListener authors.
However, in order to be compatible with a test-method scoped
TestContext (which takes its values from the current Jupiter
ExtensionContext), existing third-party TestExecutionListener
implementations may need to be modified similar to how
BeanOverrideTestExecutionListener was modified in commit d24a31d469.
To raise awareness of how to deal with such issues, this commit
documents test-method TestContext semantics for TestExecutionListener
authors.
Closes gh-35716
This commit upgrades the build to use Gradle 9.2 and reinstates the use
of the Groovy safe-navigation operator (?.) in framework-api.gradle.
See https://github.com/gradle/gradle/issues/35049
See d038269ec3
Closes gh-35713
Cache resource URLs before sorting to eliminate repeated I/O calls
during comparator operations. The previous implementation called
getURL() multiple times per resource during sorting (O(n log n)
calls), and silently swallowed IOExceptions by returning 0,
potentially causing unstable sort results.
This change:
- Caches URLs once per resource before sorting (O(n) I/O calls)
- Removes unnecessary ArrayList conversions
- Provides clear exception handling with context
- Improves performance by ~70% for typical use cases
Signed-off-by: Park Juhyeong <wngud5957@naver.com>
This commit adapts the MyBeanRegistrar Kotlin code sample to use a
lambda supplier instead of a callable reference since this capability
has been removed.
See gh-35549
Closes gh-35694
Prior to this commit, getPubliclyAccessibleMethodIfPossible() in
ClassUtils incorrectly returned a hidden static method as an
"equivalent" method for a static method with the same signature;
however, a static method cannot be overridden and therefore has no
"equivalent" method in a super type.
To fix that bug, this commit immediately aborts the search for an
"equivalent" publicly accessible method when the original method is a
static method.
See gh-33216
See gh-35189
See gh-35556
Closes gh-35667
Since we now officially support the TEST_METHOD ExtensionContextScope
(see gh-35676 and gh-35680), this commit introduces tests which
demonstrate that the issue raised in gh-34576 is no longer an "issue" if
the user indirectly configures the SpringExtension to use the TEST_METHOD
scope via the "junit.jupiter.extensions.testinstantiation.extensioncontextscope.default"
configuration parameter.
Historically, @Autowired fields in an enclosing class of a @Nested
test class have been injected from the ApplicationContext for the
enclosing class. If the enclosing test class and @Nested test class
share the same ApplicationContext configuration, things work as
developers expect. However, if the enclosing class and @Nested test
class have different ApplicationContexts, that can lead to
difficult-to-debug scenarios. For example, a bean injected into the
enclosing test class will not participate in a test-managed transaction
in the @Nested test class (see gh-34576).
JUnit Jupiter 5.12 introduced a new ExtensionContextScope feature which
allows the SpringExtension to behave the same for @Autowired fields as
it already does for @Autowired arguments in lifecycle and test
methods. Specifically, if a developer sets the ExtensionContextScope to
TEST_METHOD — for example, by configuring the following configuration
parameter as a JVM system property or in a `junit-platform.properties`
file — the SpringExtension already supports dependency injection from
the current, @Nested ApplicationContext in @Autowired fields in an
enclosing class of the @Nested test class.
junit.jupiter.extensions.testinstantiation.extensioncontextscope.default=test_method
However, there are two scenarios that fail as of Spring Framework
6.2.12.
1. @TestConstructor configuration in @Nested class hierarchies.
2. Field injection for bean overrides (such as @MockitoBean) in
@Nested class hierarchies.
Commit 82c34f7b51 fixed the SpringExtension to support scenario #2
above.
To fix scenario #1, this commit revises
BeanOverrideTestExecutionListener's injectField() implementation to
look up the fields to inject for the "current test instance" instead of
for the "current test class".
This commit also introduces tests for both scenarios.
See gh-34576
See gh-35676
Closes gh-35680
This commit updates `JdkClientHttpRequest.TimeoutHandler` javadoc to
reference up-to-date JDK issue that tracks improvements to HTTP client's
request timeout handling.
Closes gh-35581
Signed-off-by: Vedran Pavic <vedran@vedranpavic.com>
Prior to this commit, a regexp path segment ending with a double wilcard
(like "/path**") would be incorrectly parsed as a double wildcard
segment ("/**").
This commit fixes the incorrect parsing.
See gh-35679
Prior to this commit, the `PathPattern` and `PathPatternParser` would
allow multiple-segments matching and capturing with the following:
* "/files/**" (matching 0-N segments until the end)
* "/files/{*path}" (matching 0-N segments until the end and capturing
the value as the "path" variable)
This would be only allowed as the last path element in the pattern and
the parser would reject other combinations.
This commit expands the support and allows multiple segments matching at
the beginning of the path:
* "/**/index.html" (matching 0-N segments from the start)
* "/{*path}/index.html" (matching 0-N segments until the end and capturing
the value as the "path" variable)
This does come with additional restrictions:
1. "/files/**/file.txt" and "/files/{*path}/file.txt" are invalid,
as multiple segment matching is not allowed in the middle of the
pattern.
2. "/{*path}/files/**" is not allowed, as a single "{*path}" or "/**"
element is allowed in a pattern
3. "/{*path}/{folder}/file.txt" "/**/{folder:[a-z]+}/file.txt" are
invalid because only a literal pattern is allowed right after
multiple segments path elements.
Closes gh-35679
This commit improve the reference documentation in order to:
* highlight the deprecation status of `RestTemplate`
* improve the migration guide for `RestClient`, better explaining
possible behavior differences and a migration strategy.
Closes gh-35620
This commit introduces a new isAutowirableConstructor(Executable, PropertyProvider)
overload in TestConstructorUtils and deprecates all other existing variants
for removal in 7.1.
Closes gh-35676
This commit removes JSpecify (TYPE_USE) annotations on
org.hamcrest.Matcher parameters to prevent a related
"Cannot attach type annotations" error when Hamcrest
(optional dependency) is not in the classpath with Java > 22.
Closes gh-35666
This commit uses a MultiValueMap instead of a Map to store bean
registrars, allowing to support multiple bean registrars imported by
the same configuration class.
Closes gh-35653
This commit add a test for multiple bean registrars imported by the same
configuration class.
See gh-35653
Signed-off-by: wakingrufus <wakingrufus@gmail.com>
In previous versions, HttpStatus.resolve (or valueOf) always returned
non-deprecated HTTP status for given code. This was ensured implicitly,
by placing non-deprecated enum entries before their respective
deprecations. This was not ensured for 413 Content Too Large.
See gh-35659
Signed-off-by: Damian Malczewski <damian.m.malczewski@gmail.com>
Prior to this commit, gh-35225 introduced HTTP response body
decompression support for "gzip" and "deflate" encodings for the
`JdkClientHttpRequestFactory`.
While body decompression works, the client keeps the "Content-Encoding"
and "Content-Length" response headers intact, which misleads further
response handling: the body size has changed and it is not compressed
anymore.
This commit ensures that the relevant response headers are removed from
the HTTP response after decompression.
Fixes gh-35668
This commit replaces ParameterizedTypeReference and ResolvableType
target type customization with the lambda by directly exposing
ParameterizedTypeReference methods at top level, as generics
variants of the class-based existing ones.
Closes gh-35635
Prior to this commit, Spring Framework would ship several abstract
`*View` implementations for rendering PDF, RSS or XLS documents using
well-known libraries. More recently, supporting libraries evolved a lot
with new versions and forks. Spring Framework is not in a position to
efficiently support all variants within the project.
This commit deprecates the relevant classes. Instead, libraries can
reuse existing code and ship optional support for Spring directly.
Often, updating imports and library usage is enough.
As an alternative, applications can decide to perform rendering
direclty in web handlers.
Closes gh-35451
Thanks to a proposal from @wilkinsona, this commit introduces a
try-catch block in loadBeanDefinitions(...) which throws an
IllegalStateException that provides context regarding the configuration
class and cause of the failure.
Closes gh-35631
Co-authored-by: Andy Wilkinson <andy.wilkinson@broadcom.com>
As reported in gh-34651, `DataBuffer#getByte` can be inefficient for
some implementations, as bound checks are performed for each call.
This commit introduces a new `forEachByte` method that helps with
traversing operations without paying the bound check cost for each byte.
Closes gh-35623
This commit rejects the invocation of an effectively private handler
method on a CGLIB proxied controller for both Spring MVC and Spring
WebFlux.
Closes gh-35352
Co-authored-by: Sam Brannen <104798+sbrannen@users.noreply.github.com>
Signed-off-by: Yongjun Hong <kevin0928@naver.com>
Signed-off-by: yongjunhong <yongjunh@apache.org>
Prior to this commit, the non-pattern package prefix check used
packageName.startsWith(basePackage) which incorrectly treats
"com.example2.foo" as a subpackage of "com.example".
Closes gh-35601
Signed-off-by: NeatGuyCoding <15627489+NeatGuyCoding@users.noreply.github.com>
Prior to this commit, our @Retryable support as well as a RetryPolicy
created by the RetryPolicy.Builder only matched against top-level
exceptions when filtering included/excluded exceptions thrown by a
@Retryable method or Retryable operation.
With this commit, we now match against not only top-level exceptions
but also nested causes within those top-level exceptions. This is
achieved via the new ExceptionTypeFilter.match(Throwable, boolean)
support.
See gh-35592
Closes gh-35583
Prior to this commit, ExceptionTypeFilter only provided support for
filtering based on exact matches against exception types; however, some
use cases require that filtering be applied to nested causes in a given
exception. For example, this functionality is a prerequisite for
gh-35583.
This commit introduces a new match(Throwable, boolean) method in
ExceptionTypeFilter, where the boolean flag enables matching against
nested exceptions.
See gh-35583
Closes gh-35592
Prior to this commit, ReactorResourceFactory was not restarted properly
when the ApplicationContext was resumed by the TestContext Framework
after a context pause. The reason is that the managed LoopResources
were disposed when ConfigurableApplicationContext.pause() was invoked
and reacquired when ConfigurableApplicationContext.restart() was
invoked.
To address that, this commit overrides isPauseable() in
ReactorResourceFactory to return false, thereby avoiding participation
in pause scenarios.
Closes gh-35585
Internally maintain a chain of HttpMessageConverters.ClientBuilder
consumers in addition to the List of converters.
List based methods apply to the list.
HttpMessageConverters based methods are composed into a Consumer.
At build() time prepare a single HttpMessageConverters.ClientBuilder.
Insert list based converters first.
Apply HttpMessageConverters consumers after that.
Deprecate both List methods. Eventually, HttpMessageConverters should
be the main mechanism. In the mean time we layer them as described.
Closes gh-35578
Compose consumers and apply them together from the build method
to allow multiple parties to supply consumers that collaborate
on the same HttpMessageConverters.Builder.
See gh-35578
Prior to this commit, the BeanOverrideBeanFactoryPostProcessor rejected
any attempt to override a non-singleton bean; however, due to interest
from the community, we have decided to provide support for overriding
non-singleton beans via the Bean Override mechanism — for example, when
using @MockitoBean, @MockitoSpyBean, and @TestBean.
With this commit, we now support Bean Overrides for non-singletons: for
standard JVM runtimes as well as AOT processing and AOT runtimes. This
commit also documents that non-singletons will effectively be converted
to singletons when overridden and logs a warning similar to the
following.
WARN: BeanOverrideBeanFactoryPostProcessor - Converting 'prototype' scoped bean definition 'myBean' to a singleton.
See gh-33602
See gh-32933
See gh-33800
Closes gh-35574
This commit introduces a new findAnnotatedBeans(ListableBeanFactory)
override for the existing findAnnotatedBeans(ApplicationContext) method.
Closes gh-35571
AbstractApplicationContext.applicationStartup can only be injected after the instance construction. This metrics point has no practical effect at present and can be removed safely.
Closes gh-35570
Signed-off-by: Wars <wars@wars.cat>
This commit introduces two tests to verify the status quo.
- mapAccessThroughIndexerForNonexistentKey(): demonstrates that map
access via the built-in support in the Indexer returns `null` for a
nonexistent key.
- nullAwareMapAccessor(): demonstrates that users can implement and
register a custom extension of MapAccessor which reports that it can
read any map (ignoring whether the map actually contains an entry for
the given key) and returns `null` for a nonexistent key.
See gh-35534
Prior to this commit, a NoUniqueBeanDefinitionException was thrown when
multiple primary beans were detected within a given set of beans, but
nothing was logged. For use cases where the exception is handled by
infrastructure code, it may not be obvious to the developer what the
problem is.
To address that, a TRACE message is now logged whenever multiple
competing primary beans are detected in DefaultListableBeanFactory.
Closes gh-35550
After further consideration, we have decided to revert the
nullability changes in the reactive TransactionCallback and
TransactionalOperator.
See gh-35561
Prior to this commit, configuring a custom `StringHttpMessageConverter`
would be overwritten when the `registerDefaults()` option is enabled.
Fixes gh-35563
This commit adds a reproducer for the change of behavior introduced via
https://youtrack.jetbrains.com/issue/KT-76667. The test is only broken
with Kotlin 2.2.20+ without the related fix (see previous commit).
Closes gh-35487
SingletonSupplier<T> supplier-based static methods nullability should
be refined to accept in a flexible way nullable or non-nullable T.
Closes gh-35559
Previously, if a ConfigurationBeanNameGenerator is used to parse
configuration classes, it is not invoked for `Bean` methods that provide
a specific bean name. This doesn't give a chance to an implementation to
tune such a bean, if required.
This commit updates the signature of ConfigurationBeanNameGenerator to
provide the identified bean name on the `@Bean` declaration,if any, and
to always invoke it.
Closes gh-35505
At some point, TestNG started implementing listener methods as interface
default methods, so we no longer need to override those methods with
empty implementations.
Prior to this commit, AbstractTestNGSpringContextTests was not
thread-safe with regard to tracked exceptions.
To address that, AbstractTestNGSpringContextTests now tracks the test
exception via a ThreadLocal.
Closes gh-35528
Prior to this commit, the MapAccessor for SpEL resided in the
org.springframework.context.expression package in the spring-context
module; however, it arguably should reside in the spring-expression
module so that it can be used whenever SpEL is used (without requiring
spring-context).
This commit therefore officially deprecates the MapAccessor in
spring-context for removal in favor of a new copy of the implementation
in the org.springframework.expression.spel.support package in the
spring-expression module.
Closes gh-35537
This commit adds new `GsonEncoder` and `GsonDecoder` for serializing and
deserializing JSON in a reactive fashion.
Because `Gson` itslef does not support decoding JSON in a non-blocking
way, the `GsonDecoder` does not support decoding to `Flux<*>` types.
Closes gh-27131
This commit reinstantiates checks for kotlin-reflect (via static final
fields for faster Java code paths and better native code removal) which
were removed as part of gh-34275, which did not consider the
increasingly popular use cases where kotlin-stdlib is present in the
classpath as a transitive dependency in Java applications.
Closes gh-35511
As a follow-up to gh-35461 and a comment left on the Spring Blog, we
have decided to prevent empty declarations of @ConcurrencyLimit,
thereby requiring users to explicitly declare the value for the limit.
Closes gh-35523
This commit introduces a new `limit` attribute in @ConcurrencyLimit as
an alias for the existing `value` attribute. This commit also renames
the `valueString` attribute to `limitString`.
See gh-35461
See gh-35470
Prior to this commit, the `IntrospectingClientHttpResponse` would try
and read the HTTP response stream in order to check for the presence of
a non-empty message body.
Developers reported that in some cases, an `EOFException` is thrown
instead of returning -1 from the `read()` method. This commit ensures
that this case is taken into account and that we report the response as
an empty body in these cases.
Closes gh-35361
This commit upgrades the build to use Gradle 9.1.
To achieve that, the following changes were necessary.
- Stop using Groovy safe-navigation operator (?.) in
framework-api.gradle due to a NullPointerException.
- Switch from the io.github.goooler.shadow plugin to the
com.gradleup.shadow plugin, since the former is no longer maintained
and the latter is a fork that replaces it.
Closes gh-35508
This commit fixes code generation for a bean produced by a protected
factory method. Previously only the code generated for public methods,
i.e. without a dedicated instance supplier method, was handled.
Closes gh-35486
This commit apply several refinements to PropagationContextElement:
- Capture the ThreadLocal when instantiating the
PropagationContextElement in order to support dispatchers switching
threads
- Remove the constructor parameter which is not idiomatic and breaks
the support when switching threads, and use instead the
updateThreadContext(context: CoroutineContext) parameter
- Make the kotlinx-coroutines-reactor dependency optional
- Make the properties private
The Javadoc and tests are also updated to use the
`Dispatchers.IO + PropagationContextElement()` pattern performed
outside of the suspending lambda, which is the typical use case.
Closes gh-35469
This commit adds support for Hibernate 7.1+ SqmQueryImpl class in
EntityManagerRuntimeHints, keeps the support for the former
QuerySqmImpl class for Hibernate 7.0 compatibility and adds a
related test.
Closes gh-35462
Prior to this commit, annotations were not found on parameters in an
overridden method unless the method was public. Specifically, the
search algorithm in AnnotatedMethod did not consider a protected or
package-private method in a superclass to be a potential override
candidate. This affects parameter annotation searches in
spring-messaging, spring-webmvc, spring-webflux, and any other
components that use or extend AnnotatedMethod.
To address that, this commit revises the search algorithm in
AnnotatedMethod to consider all non-final declared methods as potential
override candidates, thereby aligning with the search logic in
AnnotationsScanner for the MergedAnnotations API.
Closes gh-35349
Prior to this commit, the Micrometer context-propagation project would
help propagating information from `ThreadLocal`, Reactor `Context` and
other context objects. This is already well supported for Micrometer
Observations.
In the case of Kotlin suspending functions, the processing of tasks
would not necessarily update the `ThreadLocal` when the function is
scheduled on a different thread.
This commit introduces the `PropagationContextElement` operator that
connects the `ThreadLocal`, Reactor `Context` and Coroutine `Context`
for all libraries using the "context-propagation" project.
Applications must manually use this operator in suspending functions
like so:
```
suspend fun suspendingFunction() {
return withContext(PropagationContextElement(currentCoroutineContext())) {
logger.info("Suspending function with traceId")
}
}
```
Closes gh-35185
This commit refines the JSP view resolver documentation contribution
by using tabs for Java and XML configuration, with Java displayed by
default.
Closes gh-35444
Prior to this commit, a RetryException thrown for an
InterruptedException returned the wrong value from getRetryCount().
Specifically, the count was one more than it should have been, since the
suppressed exception list contains the initial exception as well as all
retry attempt exceptions.
To address that, this commit introduces an internal
RetryInterruptedException which accounts for this off-by-one error.
Closes gh-35434
In RetryTemplate, if we encounter an InterruptedException while
sleeping for the configured back-off duration, we throw a
RetryException with the InterruptedException as the cause.
However, prior to this commit, that RetryException propagated to the
caller without notifying the registered RetryListener.
To address that, this commit introduces a new
onRetryPolicyInterruption() callback in RetryListener as a companion to
the existing onRetryPolicyExhaustion() callback.
Closes gh-35442
In RetryTemplate, if we encounter an InterruptedException while
sleeping for the configured back-off duration, we throw a
RetryException with the InterruptedException as the cause.
However, in contrast to the specification for RetryException, we do not
currently include the exceptions for previous retry attempts as
suppressed exceptions in the RetryException which is thrown in such
scenarios.
In order to comply with the documented contract for RetryException,
this commit includes exceptions for previous attempts in the
RetryException thrown for an InterruptedException as well.
Closes gh-35434
Prior to this commit, we included the initial exception in the log
message for the initial invocation of a retryable operation; however,
we did not include the current exception in the log message for
subsequent attempts.
For consistency, we now include the current exception in log messages
for subsequent retry attempts as well.
Closes gh-35433
Since Spring Framework 4.2, DefaultContextCache supported an LRU (least
recently used) eviction policy via a custom LruCache which extended
LinkedHashMap. The LruCache reacted to LinkedHashMap's
removeEldestEntry() callback to remove the LRU context if the maxSize
of the cache was exceeded.
Due to the nature of the implementation in LinkedHashMap, the
removeEldestEntry() callback is invoked after a new entry has been
stored to the map.
Consequently, a Spring ApplicationContext (C1) was evicted from the
cache after a new context (C2) was loaded and added to the cache,
leading to failure scenarios such as the following.
- C1 and C2 share an external resource -- for example, a database.
- C2 initializes the external resource with test data when C2 is loaded.
- C1 cleans up the external resource when C1 is closed.
- C1 is loaded and added to the cache.
- C2 is loaded and added to the cache before C1 is evicted.
- C1 is evicted and closed.
- C2 tests fail, because C1 removed test data required for C2.
To address such scenarios, this commit replaces the custom LruCache
with custom LRU eviction logic in DefaultContextCache and revises
the put(MergedContextConfiguration, ApplicationContext) method to
delegate to a new evictLruContextIfNecessary() method.
This commit also introduces a new put(MergedContextConfiguration,
LoadFunction) method in the ContextCache API which is overridden by
DefaultContextCache to ensure that an evicted context is removed and
closed before a new context is loaded to take its place in the cache.
In addition, DefaultCacheAwareContextLoaderDelegate has been revised to
make use of the new put(MergedContextConfiguration, LoadFunction) API.
Closes gh-21007
Prior to this commit, gh-32097 added native support for Jetty for both
client and server integrations. The `JettyDataBufferFactory` was
promoted as a first class citizen, extracted from a private class in the
client support. To accomodate with server-side requirements, an extra
`buffer.retain()` call was performed.
While this is useful for server-side support, this introduced a bug in
the data buffer factory, as wrapping an existing chunk means that this
chunk is already retained.
This commit fixes the buffer factory implementation and moved existing
tests from mocks to actual pooled buffer implementations from Jetty.
The extra `buffer.retain()` is now done from the server support, right
before wrapping the buffer.
Fixes gh-35319
As of gh-33616, Spring now supports metadata reading with the ClassFile
API on JDK 24+ runtimes. This commit fixes a bug where
`ArrayStoreException` were thrown when reading annotation attribute
values for arrays.
Fixes gh-35252
This commit ensures that the "Accept-Encoding" header is present for HTTP
requests sent by the `JdkClientHttpRequestFactory`. Only "gzip" and
"deflate" encodings are supported.
This also adds a custom `BodyHandler` that decompresses HTTP response
bodies if the "Content-Encoding" header lists a supported variant.
This feature is enabled by default and can be disabled on the request
factory.
See gh-35225
Signed-off-by: spicydev <vivek@mirchi.dev>
[brian.clozel@broadcom.com: squash commits]
Signed-off-by: Brian Clozel <brian.clozel@broadcom.com>
This commit updates the `HttpStatus` enum with the latest changes in
RFC9110:
* deprecate "413 Payload Too Large" in favor of "413 Content Too Large"
* deprecate "418 I'm a teapot" as it was meant as a joke and is now
marked as unused
* Introduce new "421 Misdirected Request"
* deprecate "422 Unprocessable Entity" in favor of
"422 Unprocessable Content"
* deprecate "509 Bandwidth Limit Exceeded" as it's now unassigned
* deprecate "510 Not Extended" as it's now marked as "historic"
The relevant exceptions, test matchers and more have been updated as a
result.
Closes gh-32870
This commit mames `StartupStep` extend `AutoCloseable` in order to allow
the try/with resources syntax and making the `step.end()` call
transparent.
Closes gh-35277
This commit updates Jackson 3 JSON support to use JsonMapper
instead of ObjectMapper in converters, codecs and view constructors.
As a consequence, AbstractJacksonDecoder, AbstractJacksonEncoder,
AbstractJacksonHttpMessageConverter and JacksonCodecSupport are
now parameterized with <T extends ObjectMapper>.
Closes gh-35282
This commit reorders and clarifies the usage instructions for
ApplicationEvents to:
1. Recommend method parameter injection as the primary approach, since
ApplicationEvents has a per-method lifecycle
2. Clarify that ApplicationEvents is not a general Spring bean and
cannot be constructor-injected
3. Explicitly state that field injection is an alternative approach
This addresses confusion where developers expect ApplicationEvents to
behave like a regular Spring bean eligible for constructor injection.
See gh-35297
Closes gh-35335
Signed-off-by: khj68 <junthewise@gmail.com>
Adds an ObservationDocumentation and ObservationConvention implementation
that follows the OpenTelemetry semantic convention for HTTP Server
metrics and spans.
See gh-35358
Undertow does not support Servlet 6.1, we need to remove compatibility
tests as well as Undertow-specific classes for WebSocket and reactive
support.
Closes gh-35354
Prior to this commit, the MergedAnnotations support (specifically
AnnotationsScanner) and AnnotatedMethod did not find annotations on
overridden methods in type hierarchies with unresolved generics.
The reason for this is that ResolvableType.resolve() returns null for
such an unresolved type, which prevents the search algorithms from
considering such methods as override candidates.
For example, given the following type hierarchy, the compiler does not
generate a method corresponding to processOneAndTwo(Long, String) for
GenericInterfaceImpl. Nonetheless, one would expect an invocation of
processOneAndTwo(Long, String) to be @Transactional since it is
effectively an invocation of processOneAndTwo(Long, C) in
GenericAbstractSuperclass, which overrides/implements
processOneAndTwo(A, B) in GenericInterface, which is annotated with
@Transactional.
However, the MergedAnnotations infrastructure currently does not
determine that processOneAndTwo(Long, C) is @Transactional since it is
not able to determine that processOneAndTwo(Long, C) overrides
processOneAndTwo(A, B) because of the unresolved generic C.
interface GenericInterface<A, B> {
@Transactional
void processOneAndTwo(A value1, B value2);
}
abstract class GenericAbstractSuperclass<C> implements GenericInterface<Long, C> {
@Override
public void processOneAndTwo(Long value1, C value2) {
}
}
static GenericInterfaceImpl extends GenericAbstractSuperclass<String> {
}
To address such issues, this commit changes the logic in
AnnotationsScanner.hasSameGenericTypeParameters() and
AnnotatedMethod.isOverrideFor() so that they use
ResolvableType.toClass() instead of ResolvableType.resolve(). The
former returns Object.class for an unresolved generic which in turn
allows the search algorithms to properly detect method overrides in
such type hierarchies.
Closes gh-35342
Prior to this commit, a regexp path segment ending with a double wilcard
(like "/path**") would be incorrectly parsed as a double wildcard
segment ("/**").
This commit fixes the incorrect parsing.
Fixes gh-35339
Prior to this commit, RetryTemplate supplied the wrong exception to
RetryListener.onRetryPolicyExhaustion(). Specifically, the execute()
method in RetryTemplate supplied the final, composite RetryException to
onRetryPolicyExhaustion() instead of the last exception thrown by the
Retryable operation.
This commit fixes that bug by ensuring that the last exception thrown by
the Retryable operation is supplied to onRetryPolicyExhaustion().
Closes gh-35334
This commit simplifies RetryException to always require a root cause
and mark it as not nullable. Such exception is the exception thrown by
the retryable operation and should always be available as it explains
why the invocation was a candidate for retrying in the first place.
Closes gh-35332
@@ -378,7 +378,7 @@ The container also supports creating a bean with {spring-framework-api}++/beans/
. The custom arguments require dynamic introspection of a matching constructor or factory method.
Those arguments cannot be detected by AOT, so the necessary reflection hints will have to be provided manually.
. By-passing the instance supplier means that all other optimizations after creation are skipped as well.
. Bypassing the instance supplier means that all other optimizations after creation are skipped as well.
For instance, autowiring on fields and methods will be skipped as they are handled in the instance supplier.
Rather than having prototype-scoped beans created with custom arguments, we recommend a manual factory pattern where a bean is responsible for the creation of the instance.
The ahead-of-time cache is a JVM feature introduced in Java 24 via the
The ahead-of-time cache is a JVM feature introduced in Java 24 via
https://openjdk.org/jeps/483[JEP 483] that can help reduce the startup time and memory
footprint of Java applications. AOT cache is a natural evolution of https://docs.oracle.com/en/java/javase/17/vm/class-data-sharing.html[Class Data Sharing (CDS)].
footprint of Java applications. AOT cache is a natural evolution of
https://docs.oracle.com/en/java/javase/17/vm/class-data-sharing.html[Class Data Sharing (CDS)].
Spring Framework supports both CDS and AOT cache, and it is recommended that you use the
later if available in the JVM version your are using (Java 24+).
latter if available in the JVM version you are using (Java 24+).
To use this feature, an AOT cache should be created for the particular classpath of the
application. It is possible to create this cache on the deployed instance, or during a
training run performed for example when packaging the application thanks to an hook-point
training run performed for example when packaging the application thanks to a hook-point
provided by the Spring Framework to ease such use case. Once the cache is available, users
should opt in to use it via a JVM flag.
NOTE: If you are using Spring Boot, it is highly recommended to leverage its
{spring-boot-docs-ref}/packaging/efficient.html#packaging.efficient.unpacking[executable JAR unpacking support]
which is designed to fulfill the class loading requirements of both AOT cache and CDS.
which is designed to fulfill the class loading requirements of both the AOT cache and CDS.
== Creating the cache
@@ -29,14 +30,22 @@ invoked; but the lifecycle has not started, and the `ContextRefreshedEvent` has
been published.
To create the cache during the training run, it is possible to specify the `-Dspring.context.exit=onRefresh`
JVM flag to start then exit your Spring application once the
JVM flag to start and then exit your Spring application once the
With https://docs.micrometer.io/micrometer/reference/concepts.html[Micrometer], developers can instrument libraries and applications for metrics (timers, gauges, counters)
that collect statistics about their runtime behavior. Metrics can help you to track error rates, usage patterns, performance, and more.
https://docs.micrometer.io/tracing/reference/[Micrometer can also produce traces], giving you a holistic view of an entire system, crossing application boundaries; you can zoom in on particular user requests and follow their entire completion across applications.
Micrometer defines an {micrometer-docs}/observation.html[Observation concept that enables both Metrics and Traces] in applications.
Metrics support offers a way to create timers, gauges, or counters for collecting statistics about the runtime behavior of your application.
Metrics can help you to track error rates, usage patterns, performance, and more.
Traces provide a holistic view of an entire system, crossing application boundaries; you can zoom in on particular user requests and follow their entire completion across applications.
Each observation will produce:
* https://docs.micrometer.io/micrometer/reference/observation/components.html#micrometer-observation-default-meter-handler[several metrics - a timer, a long task timer and many counters]
* a https://docs.micrometer.io/tracing/reference/glossary.html[span for the current trace]
Spring Framework instruments various parts of its own codebase to publish observations if an `ObservationRegistry` is configured.
You can learn more about {spring-boot-docs-ref}/actuator/observability.html[configuring the observability infrastructure in Spring Boot].
@@ -189,13 +194,13 @@ This observation uses the `io.micrometer.jakarta9.instrument.jms.DefaultJmsProce
[[observability.http-server]]
== HTTP Server instrumentation
HTTP server exchange observations are created with the name `"http.server.requests"` for Servlet and Reactive applications.
HTTP server exchange observations are created with the name `"http.server.requests"` for Servlet and Reactive applications,
or `"http.server.request.duration"` if using the OpenTelemetry convention.
[[observability.http-server.servlet]]
=== Servlet applications
Applications need to configure the `org.springframework.web.filter.ServerHttpObservationFilter` Servlet filter in their application.
It uses the `org.springframework.http.server.observation.DefaultServerRequestObservationConvention` by default, backed by the `ServerRequestObservationContext`.
This will only record an observation as an error if the `Exception` has not been handled by the web framework and has bubbled up to the Servlet filter.
Typically, all exceptions handled by Spring MVC's `@ExceptionHandler` and xref:web/webmvc/mvc-ann-rest-exceptions.adoc[`ProblemDetail` support] will not be recorded with the observation.
@@ -207,6 +212,11 @@ NOTE: Because the instrumentation is done at the Servlet Filter level, the obser
Typically, Servlet container error handling is performed at a lower level and won't have any active observation or span.
For this use case, a container-specific implementation is required, such as a `org.apache.catalina.Valve` for Tomcat; this is outside the scope of this project.
[[observability.http-server.servlet.default]]
==== Default Semantic Convention
It uses the `org.springframework.http.server.observation.DefaultServerRequestObservationConvention` by default, backed by the `ServerRequestObservationContext`.
By default, the following `KeyValues` are created:
.Low cardinality Keys
@@ -228,6 +238,16 @@ By default, the following `KeyValues` are created:
|`http.url` _(required)_|HTTP request URI.
|===
[[observability.http-server.servlet.otel]]
==== OpenTelemetry Semantic Convention
An OpenTelemetry variant is available with `org.springframework.http.server.observation.OpenTelemetryServerRequestObservationConvention`, backed by the `ServerRequestObservationContext`.
This variant complies with the https://github.com/open-telemetry/semantic-conventions/blob/v1.36.0/docs/http/http-metrics.md[OpenTelemetry Semantic Conventions for HTTP Metrics (v1.36.0)]
and the https://github.com/open-telemetry/semantic-conventions/blob/v1.36.0/docs/http/http-spans.md[OpenTelemetry Semantic Conventions for HTTP Spans (v1.36.0)].
* xref:integration/rest-clients.adoc#rest-resttemplate[`RestTemplate`] -- synchronous client with template method API, now deprecated in favor of `RestClient`
* xref:integration/rest-clients.adoc#rest-http-service-client[HTTP Service Clients] -- annotated interface backed by generated proxy
[[rest-restclient]]
@@ -402,6 +402,27 @@ To serialize only a subset of the object properties, you can specify a {baeldung
.toBodilessEntity();
----
==== URL encoded Forms
URL encoded forms, using the `"application/x-www-form-urlencoded"` media type, are useful for sending String key/values over the wire.
This is supported by the `FormHttpMessageConverter`, if the application uses a `MultiValueMap<String, String>` as source instance
or a target type.
For example:
[source,java,indent=0,subs="verbatim"]
----
MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
To send multipart data, you need to provide a `MultiValueMap<String, Object>` whose values may be an `Object` for part content, a `Resource` for a file part, or an `HttpEntity` for part content with headers.
In most cases, you do not have to specify the `Content-Type` for each part.
The content type is determined automatically based on the `HttpMessageConverter` chosen to serialize it or, in the case of a `Resource`, based on the file extension.
If necessary, you can explicitly provide the `MediaType` with an `HttpEntity` wrapper.
Once the `MultiValueMap` is ready, you can use it as the body of a `POST` request, using `RestClient.post().body(parts)` (or `RestTemplate.postForObject`).
The `Content-Type` is set to `multipart/form-data` by the `MultipartHttpMessageConverter`.
As seen in the previous section, `MultiValueMap` types can also be used for URL encoded forms.
It is preferable to explicitly set the media type in the `Content-Type` or `Accept` HTTP request headers to ensure that the expected
message converter is used.
`RestClient` can also receive multipart responses.
To decode a multipart response body, use a `ParameterizedTypeReference<MultiValueMap<String, Part>>`.
The decoded map contains `Part` instances where `FormFieldPart` represents form field values
and `FilePart` represents file parts with a `filename()` and a `transferTo()` method.
[tabs]
======
Java::
+
[source,java,indent=0,subs="verbatim"]
----
MultiValueMap<String, Part> result = this.restClient.get()
@@ -250,3 +250,29 @@ For Kotlin `Flow`, a `Flow<T>.transactional` extension is provided.
}
}
----
[[coroutines.propagation]]
== Context Propagation
Spring applications are xref:integration/observability.adoc[instrumented with Micrometer for Observability support].
For tracing support, the current observation is propagated through a `ThreadLocal` for blocking code,
or the Reactor `Context` for reactive pipelines. But the current observation also needs to be made available
in the execution context of a suspended function. Without that, the current "traceId" will not be automatically
prepended to logged statements from coroutines.
The {spring-framework-api-kdoc}/spring-core/org.springframework.core/-propagation-context-element/index.html[`PropagationContextElement`] operator generally ensures that the
{micrometer-context-propagation-docs}/[Micrometer Context Propagation library] works with Kotlin Coroutines.
It requires the `io.micrometer:context-propagation` dependency and optionally the
`org.jetbrains.kotlinx:kotlinx-coroutines-reactor` one. Automatic context propagation via
`CoroutinesUtils#invokeSuspendingFunction` (used by Spring to adapt Coroutines to Reactor `Flux` or `Mono`) can be
enabled by invoking `Hooks.enableAutomaticContextPropagation()`.
Applications can also use `PropagationContextElement` explicitly to augment the `CoroutineContext`
and registering it by using the `resolver` attribute of `@ActiveProfiles`.
NOTE: When `@ActiveProfiles` is declared on a test class, the `spring.profiles.active`
property (whether configured as a JVM system property or environment variable) is not
taken into account by the TestContext Framework when determining active profiles. If
you need to allow `spring.profiles.active` to override the profiles configured via
`@ActiveProfiles`, you can implement a custom `ActiveProfilesResolver` as described in
xref:testing/testcontext-framework/ctx-management/env-profiles.adoc[Context Configuration with Environment Profiles].
See xref:testing/testcontext-framework/ctx-management/env-profiles.adoc[Context Configuration with Environment Profiles],
xref:testing/testcontext-framework/support-classes.adoc#testcontext-junit-jupiter-nested-test-configuration[`@Nested` test class configuration], and the
{spring-framework-api}/test/context/ActiveProfiles.html[`@ActiveProfiles`] javadoc for
that we get from WebDriver. However, Geb makes things even easier by taking care of some
of the boilerplate code for us.
[[mockmvc-server-htmlunit-geb-setup]]
== MockMvc and Geb Setup
@@ -28,7 +28,8 @@ def setup() {
----
NOTE: This is a simple example of using `MockMvcHtmlUnitDriverBuilder`. For more advanced
usage, see xref:testing/mockmvc/htmlunit/webdriver.adoc#spring-mvc-test-server-htmlunit-webdriver-advanced-builder[Advanced `MockMvcHtmlUnitDriverBuilder`].
In the previous sections, we have seen how to use MockMvc in conjunction with the raw
HtmlUnit APIs. In this section, we use additional abstractions within the Selenium
https://docs.seleniumhq.org/projects/webdriver/[WebDriver] to make things even easier.
https://www.selenium.dev/documentation/webdriver/[WebDriver] to make things even easier.
[[mockmvc-server-htmlunit-webdriver-why]]
== Why WebDriver and MockMvc?
@@ -12,8 +12,8 @@ We can already use HtmlUnit and MockMvc, so why would we want to use WebDriver?
Selenium WebDriver provides a very elegant API that lets us easily organize our code. To
better show how it works, we explore an example in this section.
NOTE: Despite being a part of https://docs.seleniumhq.org/[Selenium], WebDriver does not
require a Selenium Server to run your tests.
NOTE: Despite being a part of https://www.selenium.dev/documentation/[Selenium],
WebDriver does not require a Selenium Server to run your tests.
Suppose we need to ensure that a message is created properly. The tests involve finding
the HTML form input elements, filling them out, and making various assertions.
@@ -203,7 +203,7 @@ Kotlin::
======
NOTE: This is a simple example of using `MockMvcHtmlUnitDriverBuilder`. For more advanced
usage, see xref:testing/mockmvc/htmlunit/webdriver.adoc#spring-mvc-test-server-htmlunit-webdriver-advanced-builder[Advanced `MockMvcHtmlUnitDriverBuilder`].
usage, see <<mockmvc-server-htmlunit-webdriver-advanced-builder>>.
The preceding example ensures that any URL that references `localhost` as the server is
directed to our `MockMvc` instance without the need for a real HTTP connection. Any other
@@ -259,10 +259,11 @@ Kotlin::
======
--
This improves on the design of our xref:testing/mockmvc/htmlunit/mah.adoc#spring-mvc-test-server-htmlunit-mah-usage[HtmlUnit test]
by leveraging the Page Object Pattern. As we mentioned in
xref:testing/mockmvc/htmlunit/webdriver.adoc#spring-mvc-test-server-htmlunit-webdriver-why[Why WebDriver and MockMvc?], we can use the Page Object Pattern
with HtmlUnit, but it is much easier with WebDriver. Consider the following
<<mockmvc-server-htmlunit-webdriver-why>>, we can use the Page Object Pattern with
HtmlUnit, but it is much easier with WebDriver. Consider the following
`CreateMessagePage` implementation:
--
@@ -307,7 +308,7 @@ interested. These are of type `WebElement`. WebDriver's
https://github.com/SeleniumHQ/selenium/wiki/PageFactory[`PageFactory`] lets us remove a
lot of code from the HtmlUnit version of `CreateMessagePage` by automatically resolving
method automatically resolves each `WebElement` by using the field name and looking it up
by the `id` or `name` of the element within the HTML page.
<3> We can use the
@@ -562,7 +563,19 @@ Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes"]
----
// Not possible in Kotlin until {kotlin-issues}/KT-22208 is fixed
val mockMvc: MockMvc = MockMvcBuilders
.webAppContextSetup(context)
.apply<DefaultMockMvcBuilder>(springSecurity())
.build()
driver = MockMvcHtmlUnitDriverBuilder
.mockMvcSetup(mockMvc)
// for illustration only - defaults to ""
.contextPath("")
// By default MockMvc is used for localhost only;
// the following will use MockMvc for example.com and example.org as well
.useMockMvcForHosts("example.com", "example.org")
.build()
----
======
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.