Compare commits

..

193 Commits

Author SHA1 Message Date
Stéphane Nicoll d5da602bc2 Release v6.2.2 2025-01-16 09:19:54 +01:00
rstoyanchev 384d2749c6 Polishing in HttpServiceMethod 2025-01-15 19:03:00 +00:00
rstoyanchev 5150a9a6ad Polishing contribution
Closes gh-34230
2025-01-15 18:31:50 +00:00
Yanming Zhou a8c5885aff Fix wrong document about RequestHeaderArgumentResolver
Also test is added to verify that.

Signed-off-by: Yanming Zhou <zhouyanming@gmail.com>

See gh-34230
2025-01-15 18:31:49 +00:00
Juergen Hoeller 7d844274dc Upgrade to Jetty 12.0.16, Netty 4.1.117, Protobuf 4.29.3, Checkstyle 10.21.1 2025-01-15 18:27:49 +01:00
Juergen Hoeller 70ceb3abdf Refer to local Consumer type instead of Kotlin test type 2025-01-15 17:41:22 +01:00
Sam Brannen 9181cce65f Support @⁠MockitoBean at the type level on test classes
Prior to this commit, @⁠MockitoBean could only be declared on fields
within test classes, which prevented developers from being able to
easily reuse mock configuration across a test suite.

With this commit, @⁠MockitoBean is now supported at the type level on
test classes, their superclasses, and interfaces implemented by those
classes. @⁠MockitoBean is also supported on enclosing classes for
@⁠Nested test classes, their superclasses, and interfaces implemented
by those classes, while honoring @⁠NestedTestConfiguration semantics.

In addition, @⁠MockitoBean:

- has a new `types` attribute that can be used to declare the type or
  types to mock when @⁠MockitoBean is declared at the type level

- can be declared as a repeatable annotation at the type level

- can be declared as a meta-annotation on a custom composed annotation
  which can be reused across a test suite (see the @⁠SharedMocks
  example in the reference manual)

To support these new features, this commit also includes the following
changes.

- The `field` property in BeanOverrideHandler is now @⁠Nullable.

- BeanOverrideProcessor has a new `default` createHandlers() method
  which is invoked when a @⁠BeanOverride annotation is found at the
  type level.

- MockitoBeanOverrideProcessor implements the new createHandlers()
  method.

- The internal findHandlers() method in BeanOverrideHandler has been
  completely overhauled.

- The @⁠MockitoBean and @⁠MockitoSpyBean section of the reference
  manual has been completely overhauled.

Closes gh-33925
2025-01-15 17:13:35 +01:00
Sam Brannen 8b6523a35b Cross reference @⁠NestedTestConfiguration for Bean Overrides 2025-01-15 17:13:35 +01:00
Stéphane Nicoll e7f349328d Merge pull request #34086 from rPraml
* pr/34086:
  Polish "Resolve base type in parameterized type if necessary"
  Resolve base type in parameterized type if necessary

Closes gh-34086
2025-01-15 17:07:58 +01:00
Stéphane Nicoll fe5f5d53b2 Polish "Resolve base type in parameterized type if necessary"
See gh-34086
2025-01-15 17:06:05 +01:00
Roland Praml 033d277bcf Resolve base type in parameterized type if necessary
See gh-34086
2025-01-15 17:03:20 +01:00
Juergen Hoeller 227385083d Restrict lenient nested matching to immediate type variable
Includes fix for matching multiple wildcard bounds properly.

Closes gh-34119
Closes gh-34234
2025-01-15 15:02:46 +01:00
Stéphane Nicoll d280358e98 Fix typo in HttpHeadersAssert#doesNotContainHeaders
This commit deprecates the existing doesNotContainsHeaders in favor of a
newly introduced method that does not have the typo.

Closes gh-34263
2025-01-15 11:19:00 +01:00
Stéphane Nicoll e08a7ece61 Merge pull request #34223 from remeio
* pr/34223:
  Polish contribution
  Polish HttpEntityMethodProcessor

Closes gh-34223
2025-01-14 17:36:45 +01:00
Stéphane Nicoll 24fa9ea394 Polish contribution
See gh-34223
2025-01-14 17:30:39 +01:00
Mengqi Xu 4acd9ee69b Polish HttpEntityMethodProcessor
Signed-off-by: Mengqi Xu <2663479778@qq.com>

See gh-34223
2025-01-14 17:28:00 +01:00
Stéphane Nicoll cd1aefa5e0 Upgrade to Reactor 2024.0.2
Closes gh-34252
2025-01-14 16:36:43 +01:00
Sam Brannen 3c3b8c7aac Track only qualifier annotations in BeanOverrideHandler
Closes gh-34260
2025-01-14 11:35:00 +01:00
Sam Brannen 5a68d1f029 Remove @⁠FunctionalInterface declaration from BeanOverrideProcessor
Closes gh-34259
2025-01-14 11:29:45 +01:00
Sam Brannen ff9b7678a7 Polish Bean Override internals and tests 2025-01-14 11:25:37 +01:00
Brian Clozel 799566573a Fix Wrong parentId tracking in JFR application startup
This commit fixes the tracking of the main event parentId for the Java
Flight Recorder implementation variant.

Fixes gh-34128
2025-01-13 19:03:43 +01:00
Juergen Hoeller 467d5f3ca3 Try late locking for waiting on specific bean to be finished
Closes gh-34186
2025-01-13 17:48:13 +01:00
Stéphane Nicoll 172c25fb0e Upgrade to Micrometer 1.14.3
Closes gh-34251
2025-01-13 13:54:47 +01:00
Juergen Hoeller 8771b9ea21 Defensively acquire singleton lock for FactoryBean type check
Closes gh-34247
2025-01-13 13:04:42 +01:00
Juergen Hoeller ff72652890 Defensively check expected type for qualified bean
Closes gh-34187
2025-01-13 13:03:25 +01:00
Stéphane Nicoll a1503a59ee Start building against Reactor 2024.0.2 snapshots
See gh-34252
2025-01-13 09:09:19 +01:00
Stéphane Nicoll 5f29df3ac3 Start building against Micrometer 1.14.3 snapshots
See gh-34251
2025-01-13 09:08:06 +01:00
Juergen Hoeller 25287205ba Use ReentrantLock for compilation without synchronization
Closes gh-34133
2025-01-12 18:11:47 +01:00
Juergen Hoeller 2bb4df79c3 Ignore SQLServerException with "not supported" message
Closes gh-34233
2025-01-12 18:08:54 +01:00
Juergen Hoeller 36fd82f32f Defensively resolve JarFile from JarURLConnection
Closes gh-34216
2025-01-12 18:07:09 +01:00
Juergen Hoeller 0f26f42da7 Defensively check for jar separator in jar entry names
Closes gh-34126
2025-01-12 18:05:49 +01:00
Juergen Hoeller c48fec885c Avoid caching invalid root directories
Closes gh-34111
2025-01-12 18:00:10 +01:00
Stéphane Nicoll 7c4351ab0a Polish
See gh-34231
2025-01-11 12:35:42 +01:00
rstoyanchev 07455b10f3 Use response decorator to check if error handled
Closes gh-34231
2025-01-10 10:51:39 +01:00
rstoyanchev a72855b2b3 DefaultResponseErrorHandler updates
Deprecate handleError(response), and ensure it continues to be invoked
if overridden.

See gh-34231
2025-01-10 10:51:11 +01:00
rstoyanchev cdddf09c20 Polishing in DefaultResponseErrorHandler
See gh-34231
2025-01-10 10:50:41 +01:00
xumengqi 53b3b934fc BindException declared but not handled by ExceptionHandler
Closes gh-34214

Signed-off-by: Mengqi Xu <2663479778@qq.com>
2025-01-08 16:29:12 +01:00
Brian Clozel 9173e13f74 Document that http.client.requests measure the entire HTTP exchange
Closes gh-34201
2025-01-08 14:39:50 +01:00
Brian Clozel 84be0d85b4 Refine location checks for PathResource
This commit ensures that checks for PathResource locations are skipped
because this resource implementation will always resolve under the
current location.

Closes gh-34167
2025-01-08 10:55:22 +01:00
Brian Clozel c971276f34 Refine default filtered headers for web data binding
Prior to this commit, HTTP request data binding had been improved to
filter out by default the "Priority" header in #34039.

This commit extends the set of filtered header names with:
"Accept", "Authorization", "Connection", "Cookie", "From", "Host",
"Origin", "Priority", "Range", "Referer", "Upgrade".

If an application wishes to let those header be bound, it will need to
configure the binder and replace the default header predicate by calling
`setHeaderPredicate`.

Closes gh-34182
2025-01-07 22:11:41 +01:00
Sam Brannen cd2fbb1ec5 Properly resolve @⁠TestBean factory method within class hierarchy
Prior to this commit, the search algorithm used to locate a @⁠TestBean
factory method within a test class hierarchy incorrectly found factory
methods declared in subclasses or nested test classes "below" the class
in which the @⁠TestBean field was declared. This resulted in "duplicate
bean override" failures for @⁠TestBean overrides which are clearly not
duplicates but rather "overrides of an override".

This commit ensures that @⁠TestBean factory method resolution is
consistent in type hierarchies as well as in enclosing class
hierarchies (for @⁠Nested test classes) by beginning the search for a
factory method in the class which declares the @⁠TestBean field.

Closes gh-34204
2025-01-07 17:20:52 +02:00
Sam Brannen e8745522fc Polishing 2025-01-07 11:52:33 +02:00
Brian Clozel 2bfb283c91 Update CONTRIBUTING guidelines for DCO
The CLA process has been replaced with a DCO, this commit updates the
CONTRIBUTING guidelines accordingly.
See https://spring.io/blog/2025/01/06/hello-dco-goodbye-cla-simplifying-contributions-to-spring
2025-01-07 09:55:36 +01:00
Mattias-Sehlstedt 50b1fb0b15 Change the description for the uri client request observation
This commit describes what parts that are removed from the URI template
keyvalue.

Closes: gh-34116
Signed-off-by: Mattias-Sehlstedt <60173714+Mattias-Sehlstedt@users.noreply.github.com>
2025-01-07 09:02:25 +01:00
rstoyanchev a985b73939 Improve logging in ReactiveTypeHandler
See gh-34188
2025-01-06 12:13:29 +00:00
rstoyanchev 6ec7dcf2c1 Synchronize in WebAsyncManager onError/onTimeout
On connection loss, in a race between application thread and onError
callback trying to set the DeferredResult and dispatch, the onError
callback must not exit until dispatch completes. Currently, it may do
so because the DeferredResult has checks to bypasses locking or even
trying to dispatch if result is already set.

Closes gh-34192
2025-01-06 12:06:43 +00:00
rstoyanchev d94e04d97a Minor refactoring in WebAsyncManager
There is no need to set the DeferredResult from WebAsyncManager in an
onError notification because it is already done from the Lifecycle
interceptor in DeferredResult.

See gh-34192
2025-01-06 12:06:43 +00:00
rstoyanchev 5a44897c55 Polishing in WebAsyncManager
See gh-34192
2025-01-06 12:06:43 +00:00
Sam Brannen 181db1db75 Update copyright headers to 2025 2025-01-05 17:00:47 +02:00
Sam Brannen 138bdc597d Upgrade to AssertJ 3.27.2 2025-01-05 12:28:23 +02:00
Sam Brannen ef4f1f0a71 Ensure @⁠BeanOverride in subclass takes precedence over superclass
Prior to this commit, a @⁠BeanOverride (such as @⁠TestBean) for a
specific target bean which was declared in a superclass always took
precedence over a bean override for the same target bean in a subclass,
thereby rendering the bean override configuration in the subclass
useless. In other words, there was no way for a test class to override
a bean override declared in a superclass.

To address that, this commit switches from direct use of
ReflectionUtils.doWithFields() to a custom search algorithm that
traverses the class hierarchy using tail recursion for processing
@⁠BeanOverride fields (delegating now to
ReflectionUtils.doWithLocalFields() in order to continue to benefit
from the caching of declared fields in ReflectionUtils).

Closes gh-34194
2025-01-04 18:27:05 +02:00
Sam Brannen 51b89743e1 Polishing 2025-01-04 18:12:13 +02:00
Sam Brannen 019f76468b Revise TestBeanForInheritanceIntegrationTests
Amongst other refinements, this commit ensures that the "anotherBean"
use case is actually tested.
2025-01-04 14:16:59 +02:00
Stéphane Nicoll f802c0cf24 Restore use of MethodSource 2025-01-03 16:53:54 +01:00
Sam Brannen 0da4ae96b4 Rename internal MockitoBeans class to MockBeans
This is a prerequisite for gh-33925 which will introduce a public
@MockitoBeans container annotation in the same package.
2025-01-03 17:26:45 +02:00
Sam Brannen 2ba0022704 Polishing 2025-01-03 17:26:45 +02:00
Stéphane Nicoll c59ca087b4 Backport tests for exact match resolution
See gh-34124

(cherry picked from commit 898d3ec86a)
2025-01-03 17:10:17 +02:00
Sam Brannen 9de2b947cb Upgrade to AssertJ 3.27.1 2025-01-03 16:42:07 +02:00
Sam Brannen e73e7564d0 Upgrade to Mockito 5.15.2 2025-01-03 16:36:39 +02:00
Brian Clozel d927d64c40 Improve query params in uri KeyValue with HTTP interface client
Prior to this commit, the HTTP interface client would create URI
templates and name query params like so:
"?{queryParam0}={queryParam0[0]}".
While technically correct, the URI template is further used in
observations as a KeyValue. This means that several service methods
could result in having the exact same URI template even if they produce
a different set of query params.

This commit improves the naming of query params in the generated URI
templates for better observability integration.

Closes gh-34176
2025-01-02 20:00:38 +01:00
Stéphane Nicoll 8544435833 Merge pull request #34180 from v-perfilev
* pr/34180:
  Polish "Fix broken link to Code of Conduct in CONTRIBUTING.md"
  Fix broken link to Code of Conduct in CONTRIBUTING.md

Closes gh-34180
2025-01-01 10:08:39 +01:00
Stéphane Nicoll 80ea1f62b6 Polish "Fix broken link to Code of Conduct in CONTRIBUTING.md"
See gh-34180
2025-01-01 10:08:18 +01:00
Vladimir Perfilev bc287918f2 Fix broken link to Code of Conduct in CONTRIBUTING.md
See gh-34180
2025-01-01 10:07:29 +01:00
Stéphane Nicoll c9436992c9 Update actions in CI build 2024-12-31 09:49:43 +01:00
rstoyanchev 4350fc21b3 List constructor arg initialized correctly
DataBinder now uses the calculated List size rather than
the number of indexes to initialize the list.

Closes gh-34145
2024-12-30 14:47:26 +00:00
rstoyanchev 59ed4686c5 Create ParameterErrors for type level constraint
Closes gh-34105
2024-12-30 14:47:26 +00:00
Sébastien Deleuze d5bebd5ced Upgrade to Java 17.0.13 2024-12-30 12:15:24 +01:00
Johnny Lim 6d86b23fbe Apply Checkstyle MethodParamPadCheck module
This commit also fixes its violations.

Closes gh-34173
2024-12-30 09:02:06 +01:00
Simon Baslé 0f38c28e91 Fix ServletRequestDataBinder ctor binding with []-indexed query params
This change ensures that a request containing query parameters in the
array format `someArray[]=value` can be bound into a simple array in
constructors, even for cases where the array values don't have nested
properties.

The value resolver is directly called in the constructor case, before
any mutable properties are considered or even cleared (see
`WebDataBinder#adaptEmptyArrayIndices` method). As a result, we need to
accommodate the possibility that the request stores array elements under
the `name[]` key rather than `name`. This change attempts a secondary
lookup with the `[]` suffix if the type is a list or array, and the key
doesn't include an index.

Closes gh-34121
2024-12-27 10:59:15 +01:00
Simon Baslé 3505c4bcad Ensure DataBinder can bind constructor with a Map with simple values
This change ensures that DataBinder can bind constructor with a Map
parameter that has no nested properties, but just simple values like
a String: `someMap[0]=exampleString`.

Integration tests have been added to cover similar cases that use the
ServletRequestDataBinder.

Closes gh-34043
2024-12-27 10:57:30 +01:00
Stéphane Nicoll 58670db46e Merge pull request #34165 from brendenehlers
* pr/34165:
  Polish contribution
  Fix grammatical structure in "Basic Concepts"

Closes gh-34165
2024-12-27 09:31:47 +01:00
Stéphane Nicoll 0cdb8a1657 Polish contribution
Using commas render better than em dashes.

See gh-34165
2024-12-27 09:31:34 +01:00
Brenden Ehlers fe8c70dddb Fix grammatical structure in "Basic Concepts"
See gh-34165
2024-12-27 09:30:43 +01:00
Sébastien Deleuze 1ed74efa6b Polishing
Closes gh-34148
2024-12-26 13:16:09 +01:00
Brenden Ehlers eabd574038 Fix XML code snippet
See gh-34148
2024-12-26 13:15:51 +01:00
Stéphane Nicoll ea386c2398 Merge pull request #34149 from brendenehlers
* pr/34149:
  Fix typo in link

Closes gh-34149
2024-12-25 09:29:52 +01:00
Brenden Ehlers 6c6e8ad831 Fix typo in link
See gh-34149
2024-12-25 09:29:29 +01:00
Sébastien Deleuze 69b74d7645 Fix NullPointerException in HttpComponentsClientHttpResponse
Closes gh-34132
2024-12-23 15:34:04 +01:00
Stéphane Nicoll 5ce5647d09 Restore support of exact match property
This commit fixes a regression in property placeholder resolution where
the original key was no longer considered for an exact match before
processing the placeholder itself.

By default, property resolution uses ':' as the separator between the
key and the fallback value.

Consider a request to resolve ${prefix://service}. Previously,
placeholder resolution would first attempt to resolve the raw text, that
is 'prefix://service', before attempting to resolve the 'prefix' key and
then use '//service' if the key did not resolve.

This commit restores that behaviour purely for backward compatible
reason.

Closes gh-34124
2024-12-23 12:19:45 +01:00
Tran Ngoc Nhan ebae02a92b Fix broken links in the web reference documentation
Closes gh-34115
2024-12-23 11:14:40 +01:00
Sam Brannen 99cb6ba0a7 Upgrade to Gradle 8.12 2024-12-21 16:02:15 +01:00
Sam Brannen 2baf70768d Upgrade to AssertJ 3.27 2024-12-21 15:49:31 +01:00
Sam Brannen 724700d708 Polishing 2024-12-21 15:31:01 +01:00
Andreas Kruck 83ba7e69ec Fix minor typo in reference documentation for Kotlin annotations
Closes gh-34134
2024-12-21 15:28:33 +01:00
Sam Brannen c1236a3340 Support varargs-only MethodHandle as SpEL function
Prior to this commit, if a MethodHandle was registered as a custom
function in the Spring Expression Language (SpEL) for a static method
that accepted only a variable argument list (for example,
`static String func(String... args)`), attempting to invoke the
registered function within a SpEL expression resulted in a
ClassCastException because the varargs array was unnecessarily wrapped
in an Object[].

This commit modifies the logic in FunctionReference's internal
executeFunctionViaMethodHandle() method to address that.

Closes gh-34109
2024-12-18 17:59:14 +01:00
luozongle01 a942362221 Fix a typo
Closes gh-34101
2024-12-17 11:40:47 +01:00
Brian Clozel 1a34b0dd87 Improve PathMatcher/PatternParser XML configuration
Prior to this commit, the MVC namespace for the XML Spring configuration
model would use the `PathMatcher` bean instance when provided like this:

```
<bean id="pathMatcher" class="org.springframework.util.AntPathMatcher"/>
<mvc:annotation-driven>
  <mvc:path-matching path-matcher="pathMatcher"/>
</mvc:annotation-driven>
<mvc:resources mapping="/resources/**" location="classpath:/static/"/>
```

With this configuration, the handler mapping for annotated controller
would use the given `AntPathMatcher` instance but the handler mapping
for resources would still use the default, which is `PathPatternParser`
since 6.0.

This commit ensures that when a custom `path-matcher` is defined, it's
consistently used for all MVC handler mappings as an alias to the
well-known bean name. This allows to use `AntPathMatcher` consistently
while working on a migration path to `PathPatternParser`

This commit also adds a new XML attribute to the path matching
configuration that makes it possible to use a custom `PathPatternParser`
instance:

```
<bean id="patternParser" class="org.springframework.web.util.pattern.PathPatternParser"/>
<mvc:annotation-driven>
  <mvc:path-matching pattern-parser="patternParser"/>
</mvc:annotation-driven>
```

Closes gh-34064
2024-12-17 10:14:18 +01:00
Sam Brannen b0fcde9aa3 Upgrade to JUnit 5.11.4
Closes gh-34095
2024-12-16 14:42:30 +01:00
Sam Brannen a89db89fc0 Polishing 2024-12-14 17:10:41 +01:00
Sam Brannen 3d0fffa8e4 Polish contribution
See gh-33945
2024-12-14 16:40:49 +01:00
Mico Piira 71f872e8bb Fix implicit variable resolution in JSP EvalTag
Prior to this commit, the order of parameters passed to
ELResolver#getValue was incorrect.

The `name` should correspond to the `property` parameter of the
`getValue` method instead the `base` parameter.

See gh-32383
See gh-33942
Closes gh-33945
2024-12-14 16:40:31 +01:00
Juergen Hoeller 54a90b20ed Avoid logger serialization behind shared EntityManager proxy
See gh-34084
2024-12-12 19:48:21 +01:00
Stéphane Nicoll d7a3971403 Merge pull request #34077 from scordio
* pr/34077:
  Polish "Prevent execution of Antora jobs on forks"
  Prevent execution of Antora jobs on forks

Closes gh-34077
2024-12-12 17:35:51 +01:00
Stéphane Nicoll cfa3463cec Polish "Prevent execution of Antora jobs on forks"
See gh-34077
2024-12-12 17:35:38 +01:00
Stefano Cordio d2264b221a Prevent execution of Antora jobs on forks
See gh-34077
2024-12-12 17:34:15 +01:00
Stéphane Nicoll 2c32601553 Add note about using @EventListener on lazy beans
Closes gh-34057
2024-12-12 17:32:18 +01:00
Sam Brannen ea8b18fbc7 Polish Javadoc for BeanOverrideHandler 2024-12-12 14:41:23 +01:00
Brian Clozel 3ab4ee2bba Next development version (v6.2.2-SNAPSHOT) 2024-12-12 10:53:14 +01:00
Juergen Hoeller 0aa721cad0 Polishing 2024-12-11 17:52:59 +01:00
Juergen Hoeller 63af572ce8 Upgrade to Jackson 2.18.2, RxJava 3.1.10, Checkstyle 10.20.2 2024-12-11 17:34:53 +01:00
Juergen Hoeller 72c2343f63 Avoid deprecated ListenableFuture name for internal class 2024-12-11 17:34:48 +01:00
rstoyanchev 8aeced9f80 Support header filtering in web data binding
Closes gh-34039
2024-12-11 16:11:22 +00:00
rstoyanchev 70c326ed30 Support headers in DataBinding via constructor args
Closes gh-34073
2024-12-11 16:10:08 +00:00
rstoyanchev 7b4e19c69b Make ExtendedServletRequestDataBinder public
Make it public and move it down to the annotations package alongside
InitBinderBindingContext. This is mirrors the hierarchy in Spring MVC
with the ExtendedServletRequestDataBinder. The change will allow
customization of the header names to include/exclude in data binding.

See gh-34039
2024-12-11 16:09:56 +00:00
rstoyanchev 3b95d2c449 Support Flux<ServerSentEvent<Fragment>> in WebFlux
Closes gh-33975
2024-12-11 16:09:38 +00:00
rstoyanchev 640e570583 Minor refactoring in ServerSentEvent
Extract re-usable method to serialize SSE fields.

See gh-33975
2024-12-11 16:09:22 +00:00
rstoyanchev 66f33a8265 MapMethodProcessor supportsParameter is more specific
Closes gh-33160
2024-12-11 16:09:01 +00:00
Juergen Hoeller 68997d8416 Avoid javadoc references to deprecated types/methods 2024-12-11 16:58:37 +01:00
Brian Clozel 52006b71bc Support Servlet error message in MockMvc assertions
Prior to this commit, `MockMvc` would support checking for the Servlet
error message as the "response status reason". While this error message
can be driven with the `@ResponseStatus` annotation, this message is not
technically the HTTP status reason listed on the response status line.

This message is provided by the Servlet container in the error page when
the `response.sendError(int, String)` method is used.

This commit adds the missing
`mvc.get().uri("/error/message")).hasErrorMessage("error message")`
assertion to check for this Servlet error message.

Closes gh-34016
2024-12-11 16:00:41 +01:00
Sam Brannen 41d9f21ab9 Log alias removal in DefaultListableBeanFactory
Prior to this commit, information was logged when a bean definition
overrode an existing bean definition, but nothing was logged when the
registration of a bean definition resulted in the removal of an alias.

With this commit, an INFO message is now logged whenever an alias is
removed in DefaultListableBeanFactory.

Closes gh-34070
2024-12-11 15:03:52 +01:00
Sam Brannen 7206b28272 Implement toString() in TestBeanOverrideHandler
Closes gh-34072
2024-12-11 12:12:35 +01:00
Brian Clozel 0c688742e1 Fix custom scheduler support for @Scheduled methods
This commit fixes a regression introduced by gh-24560, when adding
execution metadata support for scheduled tasks. The
`OutcomeTrackingRunnable` would delegate to the actual runnable but
could also hide whether it implements the `SchedulingAwareRunnable`
contract.

This commit ensures that `OutcomeTrackingRunnable` always implements
that contract and delegates to the runnable if possible, or return
default values otherwise.

Fixes gh-34058
2024-12-10 22:33:20 +01:00
Juergen Hoeller 7de1dc826a Consistently handle generics in TypeDescriptor.equals
Properly processes recursive types through always comparing generics via the top-level ResolvableType (rather than through nested TypeDescriptors with custom ResolvableType instances).

Closes gh-33932
2024-12-10 22:16:10 +01:00
Juergen Hoeller 3e3ca74020 Log provider setup failure at info level without stacktrace
Closes gh-33979
2024-12-10 16:25:57 +01:00
Juergen Hoeller 66da5d7ab9 Restore original override behavior when override allowed
Closes gh-33920
2024-12-10 16:25:49 +01:00
Stéphane Nicoll 68d6cb9d35 Upgrade to Reactor 2024.0.1
Closes gh-34051
2024-12-10 14:06:07 +01:00
Stéphane Nicoll 6649a6e0f7 Upgrade to Micrometer 1.14.2
Closes gh-34050
2024-12-10 14:05:43 +01:00
Sam Brannen 54948a4e88 Log warning when one Bean Override overrides another Bean Override
It is currently possible for one Bean Override to override another
logically equivalent Bean Override.

For example, a @⁠TestBean can override a @⁠MockitoBean, and vice versa.

In fact, it's also possible for a @⁠MockitoBean to override another
@⁠MockitoBean, for a @⁠TestBean to override a @⁠TestBean, etc.

However, there may be viable use cases for one override overriding
another override. For example, one may have a need to spy on a bean
created by a @⁠TestBean factory method.

In light of that, we do not prohibit one Bean Override from overriding
another Bean Override; however, with this commit we now log a warning
to help developers diagnose issues in case such an override is
unintentional.

For example, given the following test class, where TestConfig registers
a single bean of type MyService named "myService"...

@⁠SpringJUnitConfig(TestConfig.class)
class MyTests {

  @⁠TestBean(methodName = "example.TestUtils#createMyService")
  MyService testService;

  @⁠MockitoBean
  MyService mockService;

  @⁠Test
  void test() {
    // ...
  }
}

... running that test class results in a log message similar to the
following, which has been formatted for readability.

WARN - Bean with name 'myService' was overridden by multiple handlers:
[
 [TestBeanOverrideHandler@44b21f9f
  field = example.MyService example.MyTests.testService,
  beanType = example.MyService,
  beanName = [null],
  strategy = REPLACE_OR_CREATE
 ],
 [MockitoBeanOverrideHandler@7ee8130e
  field = example.MyService example.MyTests.mockService,
  beanType = example.MyService,
  beanName = [null],
  strategy = REPLACE_OR_CREATE,
  reset = AFTER,
  extraInterfaces = set[[empty]],
  answers = RETURNS_DEFAULTS, serializable = false
 ]
]

NOTE: The last registered BeanOverrideHandler wins. In the above
example, that means that @⁠MockitoBean overrides @⁠TestBean, resulting
in a Mockito mock for the MyService bean in the test's
ApplicationContext.

Closes gh-34056
2024-12-10 12:49:48 +01:00
Sébastien Deleuze a00ba8dbcf Revert "Reuse NoTransactionInContextException instances"
This reverts commit 8e3846991d.

Closes gh-34048
2024-12-10 11:47:56 +01:00
Stéphane Nicoll 4f815b0055 Merge pull request #33891 from youabledev
* pr/33891:
  Polish

Closes gh-33891
2024-12-10 07:47:52 +01:00
youable 5494d78018 Polish
See gh-33891
2024-12-10 07:47:42 +01:00
Sam Brannen cd60a0013b Reject identical Bean Overrides
Prior to this commit, the Bean Override feature in the Spring
TestContext Framework (for annotations such as @⁠MockitoBean and
@⁠TestBean) silently allowed one bean override to override another
"identical" bean override; however, Spring Boot's @⁠MockBean and
@⁠SpyBean support preemptively rejects identical overrides and throws
an IllegalStateException to signal the configuration error to the user.

To align with the behavior of @⁠MockBean and @⁠SpyBean in Spring Boot,
and to help developers avoid scenarios that are potentially confusing
or difficult to debug, this commit rejects identical bean overrides in
the Spring TestContext Framework.

Note, however, that it is still possible for a bean override to
override a logically equivalent bean override. For example, a
@⁠TestBean can override a @⁠MockitoBean, and vice versa.

Closes gh-34054
2024-12-09 16:00:24 +01:00
Sam Brannen 2137750591 Improve Bean Override by-name integration tests 2024-12-09 13:01:42 +01:00
Brian Clozel 13df9058a4 Introduce "unsafeAllocated" flag in TypeHint
This metadata information is required for supporting libraries using
`sun.misc.Unsafe#allocateInstance(Class<?>)`, even though Spring
Framework is not using this feature.

Closes gh-34055
2024-12-09 11:08:48 +01:00
Sam Brannen aee52b53a1 Introduce MockitoAssertions 2024-12-08 18:41:10 +01:00
Sam Brannen 92bbaa21e0 Improve test coverage for @⁠MockitoSpyBean use cases 2024-12-08 18:41:10 +01:00
Stéphane Nicoll 837579c2e5 Start building against Reactor 2024.0.1 snapshots
See gh-34051
2024-12-08 10:49:57 +01:00
Stéphane Nicoll 03a75cf03a Start building against Micrometer 1.14.2 snapshots
See gh-34050
2024-12-08 10:48:45 +01:00
Sam Brannen aa7b459803 Fix Phantom Read problem for Bean Overrides in the TestContext framework
To make an analogy to read phenomena for transactional databases, this
commit effectively fixes the "Phantom Read" problem for Bean Overrides.

A phantom read occurs when the BeanOverrideBeanFactoryPostProcessor
retrieves a set of bean names by-type twice and a new bean definition
for a compatible type has been created in the BeanFactory by a
BeanOverrideHandler between the first and second retrieval.

Continue reading for the details...

Prior to this commit, the injection of test Bean Overrides (for
example, when using @⁠MockitoBean) could fail in certain scenarios if
overrides were created for nonexistent beans "by type" without an
explicit name or qualifier. Specifically, if an override for a SubType
was created first, and subsequently an attempt was made to create an
override for a SuperType (where SubType extends SuperType), the
override for the SuperType would "override the override" for the
SubType, effectively removing the override for the SubType.
Consequently, injection of the override instance into the SubType field
would fail with an error message similar to the following.

BeanNotOfRequiredTypeException: Bean named 'Subtype#0' is expected to
be of type 'Subtype' but was actually of type 'Supertype$Mock$XHb7Aspo'

This commit addresses this issue by tracking all generated bean names
(in a generatedBeanNames set) and ensuring that a new bean override
instance is created for the current BeanOverrideHandler if a previous
BeanOverrideHandler already created a bean override instance that now
matches the type required by the current BeanOverrideHandler.

In other words, if the generatedBeanNames set already contains the
beanName that we just found by-type, we cannot "override the override",
because we would lose one of the overrides. Instead, we must create a
new override for the current handler. In the example given above, we
must end up with overrides for both SuperType and SubType.

Closes gh-34025
2024-12-07 16:51:16 +01:00
Sam Brannen 03fe1f0df3 Improve documentation for BeanOverrideBeanFactoryPostProcessor 2024-12-07 16:05:54 +01:00
Stéphane Nicoll 0d72477742 Restore user type in generated root bean definitions
This commit restores the user class in generated RootBeanDefinition
instances. Previously the CGLIB subclass was exposed. While this is
important in regular runtime as the configuration class parser operates
on the bean definition, this is not relevant for AOT as this information
is internal and captured in the instance supplier.

Closes gh-33960
2024-12-06 15:34:00 +01:00
Stéphane Nicoll d26ee8f852 Merge pull request #34031 from ngocnhan-tran1996
* pr/34031:
  Fix link to MockMvcBuilders in reference documentation

Closes gh-34031
2024-12-06 09:44:01 +01:00
Tran Ngoc Nhan 47c66f4352 Fix link to MockMvcBuilders in reference documentation
See gh-34031
2024-12-06 09:43:41 +01:00
Juergen Hoeller b5dd0a60f8 Restore lenient match against unresolvable wildcard
Closes gh-33982
2024-12-05 17:41:49 +01:00
Stéphane Nicoll e618f922c2 Resolve nested placeholders with a fallback having one
This commit fixes a regression in PlaceHolderParser where it would no
longer resolve nested placeholders for a case where the fallback has a
placeholder itself.

This is due to the Part implementations and how they are structure, and
this commit makes sure that nested resolution happens consistently.

Closes gh-34020
2024-12-05 16:59:30 +01:00
Stéphane Nicoll 81a9f3d50b Restore public type for generated instance supplier of CGLIB proxy
This commit restores the signature of instance suppliers that are
exposing a CGLIB proxy. While calling the CGLIB proxy itself, and
making it available in BeanInstanceSupplier, is needed internally, such
type should not be exposed as it is an internal concern.

This was breaking InstanceSupplier.andThen as it expects the public
type of the bean to be exposed, not it's eventual CGLIB subclass.

Closes gh-33998
2024-12-05 15:48:49 +01:00
Sébastien Deleuze c807fa597f Remove unnecessary HandshakeHandlerRuntimeHints
Those hints are not needed anymore as of Spring Framework 6.1.

Closes gh-34032
2024-12-05 15:44:09 +01:00
Juergen Hoeller 576f109987 Use JDK proxy for introduction interface without target
Closes gh-33985
2024-12-04 21:03:09 +01:00
Juergen Hoeller 384dc2a9b8 Consistently use singleton lock for FactoryBean processing
Closes gh-33972
2024-12-04 21:02:30 +01:00
Juergen Hoeller edf7f3cd43 Polishing 2024-12-04 16:41:07 +01:00
Juergen Hoeller 58c64cba2c Consistent fallback to NoUpgradeStrategyWebSocketService
Closes gh-33970
2024-12-04 16:39:41 +01:00
Juergen Hoeller 307411631d Ignore SQLFeatureNotSupportedException on releaseSavepoint
Closes gh-33987
2024-12-04 16:38:57 +01:00
Sam Brannen 8d69370b95 Consider logical equality in AdvisedSupport.MethodCacheKey#equals
Prior to this commit, the equals() implementation in AdvisedSupport's
MethodCacheKey only considered methods to be equal based on an identity
comparison (`==`), which led to duplicate entries in the method cache
for the same logical method.

This is caused by the fact that AdvisedSupport's
getInterceptorsAndDynamicInterceptionAdvice() method is invoked at
various stages with different Method instances for the same method:

1) when creating the proxy
2) when invoking the method via the proxy

The reason the Method instances are different is due to the following.

- Methods such as Class#getDeclaredMethods() and
  Class#getDeclaredMethod() always returns "child copies" of the
  underlying Method instances -- which means that `equals()` should be
  used instead of (or in addition to) `==` whenever the compared Method
  instances can come from different sources.

With this commit, the equals() implementation in MethodCacheKey now
considers methods equal based on identity or logical equality, giving
preference to the quicker identity check.

See gh-32586
Closes gh-33915
2024-12-04 12:04:02 +01:00
Brian Clozel d990449b0d Improve toString for reactive ScheduledTask
Prior to this commit, the reactive Scheduled tasks would be wrapped as a
`SubscribingRunnable` which does not implement a custom `toString`. This
would result in task metadata using the default Java `toString`
representation for those.

This commit ensures that the bean class name and method name are used
for this `toString`.

Closes gh-34010
2024-12-03 15:06:27 +01:00
rstoyanchev 15dcc449a2 Refine Reactor Netty handling of request without body
Closes gh-34003
2024-12-02 17:52:39 +00:00
Sam Brannen 320831b18a Test status quo for StaticMethodMatcherPointcut#matches invocations
This commit introduces a test which verifies how many times the
matches() method of a StaticMethodMatcherPointcut is invoked during
ApplicationContext startup as well as during actual method invocations
via the advice chain, which also indirectly tests the behavior of the
equals() implementation in AdvisedSupport.MethodCacheKey.

In addition, this commit revises BeanFactoryTransactionTests to assert
that a transaction is started for the setAge() method.

See gh-33915
2024-12-01 16:28:32 +01:00
Sam Brannen 172c8b2c35 Polish AOP tests 2024-12-01 15:32:03 +01:00
Sam Brannen 51956fad89 Test MockReset strategy for @⁠MockitoSpyBean
As a follow up to commit 0088b9c7f8, this commit introduces an
integration test which verifies that a spy created via @⁠MockitoSpyBean
using the MockReset.AFTER strategy is not reset between the refresh of
the ApplicationContext and the first use of the spy within a @⁠Test
method.

See gh-33941
See gh-33986
2024-11-29 11:27:02 +01:00
Sébastien Deleuze ddec8d2653 Add missing @Contract annotation to ObjectUtils#isEmpty
Closes gh-33984
2024-11-28 15:17:02 +01:00
Sébastien Deleuze 1aede291bb Move Kotlin value class unboxing to InvocableHandlerMethod
Before this commit, in Spring Framework 6.2, Kotlin value class
unboxing was done at CoroutinesUtils level, which is a good fit
for InvocableHandlerMethod use case, but not for other ones like
AopUtils.

This commit moves such unboxing to InvocableHandlerMethod in
order to keep the HTTP response body support while fixing other
regressions.

Closes gh-33943
2024-11-27 16:39:26 +01:00
Sam Brannen ea3bd7ae0c Polish BeanValidationBeanRegistrationAotProcessor[Tests]
The log message for a NoClassDefFoundError is now a DEBUG level message
handled like a TypeNotPresentException and similar to the following.

DEBUG: Skipping validation constraint hint inference for class
org.example.CustomConstraint due to a NoClassDefFoundError for
com.example.MissingType

See gh-33949
2024-11-27 12:53:51 +01:00
Stefano Cordio 9b0253e117 Skip runtime hint registration for constraint with missing dependencies
Prior to this commit, AOT processing for bean validation failed with a
NoClassDefFoundError for constraints with missing dependencies.

With this commit, the processing no longer fails, and a warning is
logged instead.

See gh-33940
Closes gh-33949

Co-authored-by: Sam Brannen <sam.brannen@broadcom.com>
2024-11-27 12:42:12 +01:00
Stéphane Nicoll f3753e6d64 Merge pull request #33956 from CHOICORE
* pr/33956:
  Fix log level in PathMatchingResourcePatternResolver

Closes gh-33956
2024-11-26 20:04:25 +01:00
CHOICORE 41421d106b Fix log level in PathMatchingResourcePatternResolver
See gh-33956
2024-11-26 19:51:17 +01:00
Tran Ngoc Nhan 8c0ac8e062 Fix a typo in the filters documentation
Closes gh-33959
2024-11-26 16:09:45 +01:00
Sam Brannen 0088b9c7f8 Honor MockReset strategy for @⁠MockitoBean and @⁠MockitoSpyBean
Commit 6c2cba5d8a introduced a regression by inadvertently removing the
MockReset strategy comparison when resetting @⁠MockitoBean and
@⁠MockitoSpyBean mocks.

This commit reinstates the MockReset strategy check and introduces
tests for this feature.

Closes gh-33941
2024-11-26 11:54:46 +01:00
Sam Brannen 2b840ee7ef Upgrade to Gradle 8.11.1
Closes gh-33951
2024-11-24 14:27:39 +01:00
Sam Brannen 051f1dac24 Polish contribution
See gh-33950
2024-11-24 14:13:03 +01:00
Stefano Cordio 5e7b3a3bed Avoid infinite recursion in BeanValidationBeanRegistrationAotProcessor
Prior to this commit, AOT processing for bean validation failed with a
StackOverflowError for constraints with fields having recursive generic
types.

With this commit, the algorithm tracks visited classes and aborts
preemptively when a cycle is detected.

Closes gh-33950

Co-authored-by: Sam Brannen <sam.brannen@broadcom.com>
2024-11-24 14:09:48 +01:00
Johnny Lim 1910d32405 Replace TestObservationRegistryAssert.assertThat() with Assertions.assertThat()
See https://github.com/micrometer-metrics/micrometer/pull/5551

Closes gh-33929
2024-11-21 14:35:32 +01:00
sonallux 986ffc2072 Use full URI for URI template keyvalue with RestClient
Prior to this commit, `RestClient` would not use the full URI created by
the uri handler as a template request attribute.
This means that HTTP client observations would not contain the base URI
in recorded observations as the uri template keyvalue.

Closes gh-33928
2024-11-21 14:23:01 +01:00
Sam Brannen b9cf03f8f0 Construct consistent error messages in BeanOverrideBeanFactoryPostProcessor 2024-11-21 11:28:31 +01:00
Sam Brannen 08a789cee9 Honor @⁠Fallback semantics for Test Bean Overrides
Closes gh-33924
2024-11-21 09:50:17 +01:00
Sam Brannen 7a6e401d17 Document visibility requirements for Bean Overrides
This commit makes it clear that there are no visibility requirements
for @⁠TestBean fields or factory methods as well as @⁠MockitoBean or
@⁠MockitoSpyBean fields.

Closes gh-33923
2024-11-20 16:49:52 +01:00
Sam Brannen 3569cfe990 Reject static Bean Override fields for @⁠MockitoBean, @⁠TestBean, etc.
Closes gh-33922
2024-11-20 11:29:01 +01:00
Simon Baslé 8b66d3c79a Upgrade Undertow-servlet/websockets to 2.3.18.Final
Follow up to 35b452b4 which only upgraded undertow-core.
2024-11-19 16:59:04 +01:00
Sam Brannen a3c132c442 Polish XmlExpectationsHelper[Tests] 2024-11-19 13:33:20 +01:00
boiarshinov 91791c1756 Fail with full description for XML diff in XmlExpectationsHelper
Closes gh-33827
2024-11-19 13:23:58 +01:00
Sam Brannen dd92eac3ad Refer to message "receipt" instead of "reception" 2024-11-19 13:18:12 +01:00
Sam Brannen 874f056984 Polishing 2024-11-19 13:18:12 +01:00
Tran Ngoc Nhan b77db64459 Fix typos and link in Observability documentation
Closes gh-33910
2024-11-19 12:12:01 +01:00
Simon Baslé d597d2e159 Fix WebClientIntegrationTest#applyAttributesToNativeRequest flaky test
For Reactor Netty and Reactor Netty 2 (with Netty 5), the attributes are
stored as an `Attribute` on the netty channel. Reactor Netty replaces
the channel with a static placeholder one once the request has been
processed and as such, capturing the native request in the test will
lead to asserting an attribute-less channel.

This change switches to capturing the `Attribute` itself, which is a
value-holder that can be asserted later on.

Closes gh-33909
2024-11-18 16:30:16 +01:00
Sam Brannen f5c3f3522e Simplify @⁠EnumSource usage 2024-11-18 14:12:13 +01:00
Sam Brannen d421f61a4a Polish @⁠DurationFormat Javadoc and tests 2024-11-18 14:12:13 +01:00
Tran Ngoc Nhan 883254e1d0 Polish
- Update copyright header.
- Consistent use of "SIMPLE" link text for Style#SIMPLE in javadoc.

Closes gh-33883
2024-11-18 13:40:23 +01:00
Brian Clozel e919d0adcc Reflect well-known MediaTypes intent in Javadoc
Closes gh-33754
2024-11-18 11:57:22 +01:00
Brian Clozel 4aafae1c33 Reflect well-known HttpHeaders intent in Javadoc
Closes gh-33886
2024-11-18 11:57:15 +01:00
Brian Clozel afef439c1f Temporarily disable flaky integration test
See gh-33909
2024-11-18 11:57:09 +01:00
Sam Brannen 807e1e6126 Document support for varargs invocations in SpEL
Closes gh-33332
2024-11-18 11:54:22 +01:00
Stéphane Nicoll 5ac56bda87 Remove unnecessary workflow in maintenance branch 2024-11-18 11:52:08 +01:00
Sam Brannen 7196f3f554 Polish SpEL documentation 2024-11-18 11:38:20 +01:00
Sam Brannen a12d40e10b Fix SpEL examples in reference guide
Closes gh-33907
2024-11-18 11:37:30 +01:00
Sam Brannen 7f7819329c Update copyright headers
See gh-33903
2024-11-17 15:14:16 +01:00
KNU-K 2494ecb47b Simplify utility implementations in spring-core
Closes gh-33903
2024-11-17 15:08:30 +01:00
Sam Brannen 241b8b48f2 Clarify requirements for AOP around advice regarding MethodInterceptor
Closes gh-33901
2024-11-17 12:23:01 +01:00
Sam Brannen 173084f81a Polish Spring AOP documentation 2024-11-17 12:21:16 +01:00
Sam Brannen 6544698078 Polish contribution
See gh-33902
2024-11-17 11:45:37 +01:00
taehyun e0e96c487f Simplify implementation of FilteredIterator
Closes gh-33902
2024-11-17 11:41:22 +01:00
Sam Brannen bb32df0a06 Upgrade to Gradle 8.11
Closes gh-33895
2024-11-15 16:06:14 +01:00
Brian Clozel 66c3aeee84 Polishing 2024-11-15 15:37:00 +01:00
Brian Clozel 828980bd44 Fix workflow configuration for 6.2.x branch 2024-11-15 15:35:32 +01:00
Sam Brannen fe8573c0ab Upgrade to antora-ui-spring version 0.4.18
Closes gh-33892
2024-11-15 14:32:01 +01:00
Brian Clozel 130627f630 Next development version (v6.2.1-SNAPSHOT) 2024-11-14 17:48:54 +01:00
332 changed files with 7210 additions and 2514 deletions
@@ -31,10 +31,11 @@ runs:
${{ inputs.java-early-access == 'true' && format('{0}-ea', inputs.java-version) || inputs.java-version }}
${{ inputs.java-toolchain == 'true' && '17' || '' }}
- name: Set Up Gradle
uses: gradle/actions/setup-gradle@d156388eb19639ec20ade50009f3d199ce1e2808 # v4.1.0
uses: gradle/actions/setup-gradle@cc4fc85e6b35bafd578d5ffbc76a5518407e1af0 # v4.2.1
with:
cache-read-only: false
develocity-access-key: ${{ inputs.develocity-access-key }}
develocity-token-expiry: 4
- name: Configure Gradle Properties
shell: bash
run: |
@@ -20,7 +20,7 @@ runs:
using: composite
steps:
- name: Set Up JFrog CLI
uses: jfrog/setup-jfrog-cli@9fe0f98bd45b19e6e931d457f4e98f8f84461fb5 # v4.4.1
uses: jfrog/setup-jfrog-cli@dff217c085c17666e8849ebdbf29c8fe5e3995e6 # v4.5.2
env:
JF_ENV_SPRING: ${{ inputs.jfrog-cli-config-token }}
- name: Download Release Artifacts
@@ -2,7 +2,7 @@ name: Build and Deploy Snapshot
on:
push:
branches:
- main
- 6.2.x
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
jobs:
@@ -21,7 +21,7 @@ jobs:
develocity-access-key: ${{ secrets.DEVELOCITY_ACCESS_KEY }}
publish: true
- name: Deploy
uses: spring-io/artifactory-deploy-action@26bbe925a75f4f863e1e529e85be2d0093cac116 # v0.0.1
uses: spring-io/artifactory-deploy-action@dc1913008c0599f0c4b1fdafb6ff3c502b3565ea # v0.0.2
with:
artifact-properties: |
/**/framework-api-*.zip::zip.name=spring-framework,zip.deployed=false
+3 -14
View File
@@ -9,22 +9,11 @@ jobs:
runs-on: ubuntu-latest
timeout-minutes: 60
steps:
- name: Set Up JDK 17
uses: actions/setup-java@v4
with:
distribution: 'liberica'
java-version: '17'
- name: Check Out
- name: Check Out Code
uses: actions/checkout@v4
- name: Validate Gradle Wrapper
uses: gradle/actions/wrapper-validation@d156388eb19639ec20ade50009f3d199ce1e2808 # v4.1.0
- name: Set Up Gradle
uses: gradle/actions/setup-gradle@d156388eb19639ec20ade50009f3d199ce1e2808 # v4.1.0
- name: Build
env:
CI: 'true'
GRADLE_ENTERPRISE_URL: 'https://ge.spring.io'
run: ./gradlew -Dorg.gradle.internal.launcher.welcomeMessageEnabled=false --no-daemon --no-parallel --continue build
id: build
uses: ./.github/actions/build
- name: Print JVM Thread Dumps When Cancelled
if: cancelled()
uses: ./.github/actions/print-jvm-thread-dumps
+3 -2
View File
@@ -1,7 +1,8 @@
name: CI
on:
schedule:
- cron: '30 9 * * *'
push:
branches:
- 6.2.x
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
jobs:
-79
View File
@@ -1,79 +0,0 @@
name: Release Milestone
on:
push:
tags:
- v6.2.0-M[1-9]
- v6.2.0-RC[1-9]
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
jobs:
build-and-stage-release:
if: ${{ github.repository == 'spring-projects/spring-framework' }}
name: Build and Stage Release
runs-on: ubuntu-latest
steps:
- name: Check Out Code
uses: actions/checkout@v4
- name: Build and Publish
id: build-and-publish
uses: ./.github/actions/build
with:
develocity-access-key: ${{ secrets.GRADLE_ENTERPRISE_SECRET_ACCESS_KEY }}
publish: true
- name: Stage Release
uses: spring-io/artifactory-deploy-action@26bbe925a75f4f863e1e529e85be2d0093cac116 # v0.0.1
with:
artifact-properties: |
/**/framework-api-*.zip::zip.name=spring-framework,zip.deployed=false
/**/framework-api-*-docs.zip::zip.type=docs
/**/framework-api-*-schema.zip::zip.type=schema
build-name: ${{ format('spring-framework-{0}', steps.build-and-publish.outputs.version)}}
folder: 'deployment-repository'
password: ${{ secrets.ARTIFACTORY_PASSWORD }}
repository: 'libs-staging-local'
signing-key: ${{ secrets.GPG_PRIVATE_KEY }}
signing-passphrase: ${{ secrets.GPG_PASSPHRASE }}
uri: 'https://repo.spring.io'
username: ${{ secrets.ARTIFACTORY_USERNAME }}
outputs:
version: ${{ steps.build-and-publish.outputs.version }}
verify:
name: Verify
needs: build-and-stage-release
uses: ./.github/workflows/verify.yml
with:
staging: true
version: ${{ needs.build-and-stage-release.outputs.version }}
secrets:
google-chat-webhook-url: ${{ secrets.GOOGLE_CHAT_WEBHOOK_URL }}
repository-password: ${{ secrets.ARTIFACTORY_PASSWORD }}
repository-username: ${{ secrets.ARTIFACTORY_USERNAME }}
token: ${{ secrets.GH_ACTIONS_REPO_TOKEN }}
promote-release:
name: Promote Release
needs:
- build-and-stage-release
- verify
runs-on: ubuntu-latest
steps:
- name: Set up JFrog CLI
uses: jfrog/setup-jfrog-cli@9fe0f98bd45b19e6e931d457f4e98f8f84461fb5 # v4.4.1
env:
JF_ENV_SPRING: ${{ secrets.JF_ARTIFACTORY_SPRING }}
- name: Promote build
run: jfrog rt build-promote ${{ format('spring-framework-{0}', needs.build-and-stage-release.outputs.version)}} ${{ github.run_number }} libs-milestone-local
create-github-release:
name: Create GitHub Release
needs:
- build-and-stage-release
- promote-release
runs-on: ubuntu-latest
steps:
- name: Check Out Code
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- name: Create GitHub Release
uses: ./.github/actions/create-github-release
with:
milestone: ${{ needs.build-and-stage-release.outputs.version }}
pre-release: true
token: ${{ secrets.GH_ACTIONS_REPO_TOKEN }}
+1 -1
View File
@@ -73,7 +73,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Set up JFrog CLI
uses: jfrog/setup-jfrog-cli@9fe0f98bd45b19e6e931d457f4e98f8f84461fb5 # v4.4.1
uses: jfrog/setup-jfrog-cli@dff217c085c17666e8849ebdbf29c8fe5e3995e6 # v4.5.2
env:
JF_ENV_SPRING: ${{ secrets.JF_ARTIFACTORY_SPRING }}
- name: Promote build
@@ -12,8 +12,9 @@ permissions:
jobs:
update-antora-ui-spring:
runs-on: ubuntu-latest
name: Update on Supported Branches
if: ${{ github.repository == 'spring-projects/spring-framework' }}
runs-on: ubuntu-latest
strategy:
matrix:
branch: [ '6.1.x' ]
@@ -25,8 +26,9 @@ jobs:
token: ${{ secrets.GITHUB_TOKEN }}
antora-file-path: 'framework-docs/antora-playbook.yml'
update-antora-ui-spring-docs-build:
runs-on: ubuntu-latest
name: Update on docs-build
if: ${{ github.repository == 'spring-projects/spring-framework' }}
runs-on: ubuntu-latest
steps:
- uses: spring-io/spring-doc-actions/update-antora-spring-ui@5a57bcc6a0da2a1474136cf29571b277850432bc
name: Update
+1 -1
View File
@@ -46,7 +46,7 @@ jobs:
distribution: 'liberica'
java-version: 17
- name: Set Up Gradle
uses: gradle/actions/setup-gradle@d156388eb19639ec20ade50009f3d199ce1e2808 # v4.1.0
uses: gradle/actions/setup-gradle@cc4fc85e6b35bafd578d5ffbc76a5518407e1af0 # v4.2.1
with:
cache-read-only: false
- name: Configure Gradle Properties
+1 -1
View File
@@ -1,3 +1,3 @@
# Enable auto-env through the sdkman_auto_env config
# Add key=value pairs of SDKs to use below
java=17.0.12-librca
java=17.0.13-librca
+6 -5
View File
@@ -16,7 +16,7 @@ First off, thank you for taking the time to contribute! :+1: :tada:
### Code of Conduct
This project is governed by the [Spring Code of Conduct](CODE_OF_CONDUCT.adoc).
This project is governed by the [Spring Code of Conduct](https://github.com/spring-projects/spring-framework#coc-ov-file).
By participating you are expected to uphold this code.
Please report unacceptable behavior to spring-code-of-conduct@spring.io.
@@ -65,10 +65,6 @@ follow-up reports will need to be created as new issues with a fresh description
#### Submit a Pull Request
1. If you have not previously done so, please sign the
[Contributor License Agreement](https://cla.spring.io/sign/spring). You will be reminded
automatically when you submit the PR.
1. Should you create an issue first? No, just create the pull request and use the
description to provide context and motivation, as you would for an issue. If you want
to start a discussion first or have already created an issue, once a pull request is
@@ -85,6 +81,11 @@ multiple edits or corrections of the same logical change. See
[Rewriting History section of Pro Git](https://git-scm.com/book/en/Git-Tools-Rewriting-History)
for an overview of streamlining the commit history.
1. All commits must include a _Signed-off-by_ trailer at the end of each commit message
to indicate that the contributor agrees to the Developer Certificate of Origin.
For additional details, please refer to the blog post
[Hello DCO, Goodbye CLA: Simplifying Contributions to Spring](https://spring.io/blog/2025/01/06/hello-dco-goodbye-cla-simplifying-contributions-to-spring).
1. Format commit messages using 55 characters for the subject line, 72 characters per line
for the description, followed by the issue fixed, for example, `Closes gh-22276`. See the
[Commit Guidelines section of Pro Git](https://git-scm.com/book/en/Distributed-Git-Contributing-to-a-Project#Commit-Guidelines)
+4 -4
View File
@@ -25,17 +25,17 @@ configure(allprojects) { project ->
repositories {
mavenCentral()
maven {
url "https://repo.spring.io/milestone"
url = "https://repo.spring.io/milestone"
content {
// Netty 5 optional support
includeGroup 'io.projectreactor.netty'
}
}
if (version.contains('-')) {
maven { url "https://repo.spring.io/milestone" }
maven { url = "https://repo.spring.io/milestone" }
}
if (version.endsWith('-SNAPSHOT')) {
maven { url "https://repo.spring.io/snapshot" }
maven { url = "https://repo.spring.io/snapshot" }
}
}
configurations.all {
@@ -102,7 +102,7 @@ configure([rootProject] + javaProjects) { project ->
// TODO Uncomment link to JUnit 5 docs once we execute Gradle with Java 18+.
// See https://github.com/spring-projects/spring-framework/issues/27497
//
// "https://junit.org/junit5/docs/5.11.3/api/",
// "https://junit.org/junit5/docs/5.11.4/api/",
"https://www.reactive-streams.org/reactive-streams-1.0.3-javadoc/",
//"https://javadoc.io/static/io.rsocket/rsocket-core/1.1.1/",
"https://r2dbc.io/spec/1.0.0.RELEASE/api/",
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2024 the original author or authors.
* Copyright 2002-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -50,7 +50,7 @@ public class CheckstyleConventions {
project.getPlugins().apply(CheckstylePlugin.class);
project.getTasks().withType(Checkstyle.class).forEach(checkstyle -> checkstyle.getMaxHeapSize().set("1g"));
CheckstyleExtension checkstyle = project.getExtensions().getByType(CheckstyleExtension.class);
checkstyle.setToolVersion("10.20.1");
checkstyle.setToolVersion("10.21.1");
checkstyle.getConfigDirectory().set(project.getRootProject().file("src/checkstyle"));
String version = SpringJavaFormatPlugin.class.getPackage().getImplementationVersion();
DependencySet checkstyleDependencies = project.getConfigurations().getByName("checkstyle").getDependencies();
+2 -2
View File
@@ -9,7 +9,7 @@ apply from: "${rootDir}/gradle/publications.gradle"
repositories {
maven {
url "https://repo.spring.io/release"
url = "https://repo.spring.io/release"
}
}
@@ -87,7 +87,7 @@ tasks.register('schemaZip', Zip) {
archiveClassifier.set("schema")
description = "Builds -${archiveClassifier} archive containing all " +
"XSDs for deployment at https://springframework.org/schema."
duplicatesStrategy DuplicatesStrategy.EXCLUDE
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
moduleProjects.each { module ->
def Properties schemas = new Properties();
+1 -1
View File
@@ -36,4 +36,4 @@ runtime:
failure_level: warn
ui:
bundle:
url: https://github.com/spring-io/antora-ui-spring/releases/download/v0.4.17/ui-bundle.zip
url: https://github.com/spring-io/antora-ui-spring/releases/download/v0.4.18/ui-bundle.zip
+1 -1
View File
@@ -37,7 +37,7 @@ javadoc {
repositories {
maven {
url "https://repo.spring.io/release"
url = "https://repo.spring.io/release"
}
}
+1
View File
@@ -60,6 +60,7 @@
**** xref:core/expressions/language-ref/constructors.adoc[]
**** xref:core/expressions/language-ref/variables.adoc[]
**** xref:core/expressions/language-ref/functions.adoc[]
**** xref:core/expressions/language-ref/varargs.adoc[]
**** xref:core/expressions/language-ref/bean-references.adoc[]
**** xref:core/expressions/language-ref/operator-ternary.adoc[]
**** xref:core/expressions/language-ref/operator-elvis.adoc[]
@@ -33,11 +33,11 @@ arbitrary advice types. This section describes the basic concepts and standard a
[[aop-api-advice-around]]
=== Interception Around Advice
The most fundamental advice type in Spring is interception around advice.
The most fundamental advice type in Spring is _interception around advice_.
Spring is compliant with the AOP `Alliance` interface for around advice that uses method
interception. Classes that implement `MethodInterceptor` and that implement around advice should also implement the
following interface:
Spring is compliant with the AOP Alliance interface for around advice that uses method
interception. Classes that implement around advice should therefore implement the
following `MethodInterceptor` interface from the `org.aopalliance.intercept` package:
[source,java,indent=0,subs="verbatim,quotes"]
----
@@ -49,8 +49,8 @@ following interface:
The `MethodInvocation` argument to the `invoke()` method exposes the method being
invoked, the target join point, the AOP proxy, and the arguments to the method. The
`invoke()` method should return the invocation's result: the return value of the join
point.
`invoke()` method should return the invocation's result: typically the return value of
the join point.
The following example shows a simple `MethodInterceptor` implementation:
@@ -64,9 +64,9 @@ Java::
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("Before: invocation=[" + invocation + "]");
Object rval = invocation.proceed();
Object result = invocation.proceed();
System.out.println("Invocation returned");
return rval;
return result;
}
}
----
@@ -79,9 +79,9 @@ Kotlin::
override fun invoke(invocation: MethodInvocation): Any {
println("Before: invocation=[$invocation]")
val rval = invocation.proceed()
val result = invocation.proceed()
println("Invocation returned")
return rval
return result
}
}
----
@@ -105,7 +105,7 @@ currently define pointcut interfaces.
[[aop-api-advice-before]]
=== Before Advice
A simpler advice type is a before advice. This does not need a `MethodInvocation`
A simpler advice type is a _before advice_. This does not need a `MethodInvocation`
object, since it is called only before entering the method.
The main advantage of a before advice is that there is no need to invoke the `proceed()`
@@ -122,10 +122,6 @@ The following listing shows the `MethodBeforeAdvice` interface:
}
----
(Spring's API design would allow for
field before advice, although the usual objects apply to field interception and it is
unlikely for Spring to ever implement it.)
Note that the return type is `void`. Before advice can insert custom behavior before the join
point runs but cannot change the return value. If a before advice throws an
exception, it stops further execution of the interceptor chain. The exception
@@ -176,10 +172,10 @@ TIP: Before advice can be used with any pointcut.
[[aop-api-advice-throws]]
=== Throws Advice
Throws advice is invoked after the return of the join point if the join point threw
_Throws advice_ is invoked after the return of the join point if the join point threw
an exception. Spring offers typed throws advice. Note that this means that the
`org.springframework.aop.ThrowsAdvice` interface does not contain any methods. It is a
tag interface identifying that the given object implements one or more typed throws
marker interface identifying that the given object implements one or more typed throws
advice methods. These should be in the following form:
[source,java,indent=0,subs="verbatim,quotes"]
@@ -189,9 +185,10 @@ advice methods. These should be in the following form:
Only the last argument is required. The method signatures may have either one or four
arguments, depending on whether the advice method is interested in the method and
arguments. The next two listing show classes that are examples of throws advice.
arguments. The next two listings show classes that are examples of throws advice.
The following advice is invoked if a `RemoteException` is thrown (including from subclasses):
The following advice is invoked if a `RemoteException` is thrown (including subclasses of
`RemoteException`):
[tabs]
======
@@ -220,9 +217,9 @@ Kotlin::
----
======
Unlike the preceding
advice, the next example declares four arguments, so that it has access to the invoked method, method
arguments, and target object. The following advice is invoked if a `ServletException` is thrown:
Unlike the preceding advice, the next example declares four arguments, so that it has
access to the invoked method, method arguments, and target object. The following advice
is invoked if a `ServletException` is thrown:
[tabs]
======
@@ -304,7 +301,7 @@ TIP: Throws advice can be used with any pointcut.
[[aop-api-advice-after-returning]]
=== After Returning Advice
An after returning advice in Spring must implement the
An _after returning advice_ in Spring must implement the
`org.springframework.aop.AfterReturningAdvice` interface, which the following listing shows:
[source,java,indent=0,subs="verbatim,quotes"]
@@ -368,7 +365,7 @@ TIP: After returning advice can be used with any pointcut.
[[aop-api-advice-introduction]]
=== Introduction Advice
Spring treats introduction advice as a special kind of interception advice.
Spring treats _introduction advice_ as a special kind of interception advice.
Introduction requires an `IntroductionAdvisor` and an `IntroductionInterceptor` that
implement the following interface:
@@ -578,6 +578,8 @@ Kotlin::
----
======
NOTE: Do not define such beans to be lazy as the `ApplicationContext` will honour that and will not register the method to listen to events.
The method signature once again declares the event type to which it listens,
but, this time, with a flexible name and without implementing a specific listener interface.
The event type can also be narrowed through generics as long as the actual event type
@@ -3,7 +3,7 @@
If a bean is a dependency of another bean, that usually means that one bean is set as a
property of another. Typically you accomplish this with the
xref:core/beans/dependencies/factory-properties-detailed.adoc#beans-ref-element[`<ref/>` element>]
xref:core/beans/dependencies/factory-properties-detailed.adoc#beans-ref-element[`<ref/>` element]
in XML-based metadata or through xref:core/beans/dependencies/factory-autowire.adoc[autowiring].
However, sometimes dependencies between beans are less direct. An example is when a static
@@ -168,8 +168,8 @@ listings shows how to use the `parent` attribute:
[source,xml,indent=0,subs="verbatim,quotes"]
----
<!-- in the child (descendant) context -->
<bean id="accountService" <!-- bean name is the same as the parent bean -->
<!-- in the child (descendant) context, bean name is the same as the parent bean -->
<bean id="accountService"
class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target">
<ref parent="accountService"/> <!-- notice how we refer to the parent bean -->
@@ -64,7 +64,7 @@ This prevents the same `@Bean` method from accidentally being invoked through a
Java method call, which helps to reduce subtle bugs that can be hard to track down.
When `@Bean` methods are declared within classes that are not annotated with
`@Configuration` - or when `@Configuration(proxyBeanMethods=false)` is declared -,
`@Configuration`, or when `@Configuration(proxyBeanMethods=false)` is declared,
they are referred to as being processed in a "lite" mode. In such scenarios,
`@Bean` methods are effectively a general-purpose factory method mechanism without
special runtime processing (that is, without generating a CGLIB subclass for it).
@@ -3,8 +3,10 @@
You can invoke constructors by using the `new` operator. You should use the fully
qualified class name for all types except those located in the `java.lang` package
(`Integer`, `Float`, `String`, and so on). The following example shows how to use the
`new` operator to invoke constructors:
(`Integer`, `Float`, `String`, and so on).
xref:core/expressions/language-ref/varargs.adoc[Varargs] are also supported.
The following example shows how to use the `new` operator to invoke constructors.
[tabs]
======
@@ -12,30 +14,29 @@ Java::
+
[source,java,indent=0,subs="verbatim,quotes"]
----
Inventor einstein = p.parseExpression(
"new org.spring.samples.spel.inventor.Inventor('Albert Einstein', 'German')")
Inventor einstein = parser.parseExpression(
"new org.spring.samples.spel.inventor.Inventor('Albert Einstein', 'German')")
.getValue(Inventor.class);
// create new Inventor instance within the add() method of List
p.parseExpression(
"Members.add(new org.spring.samples.spel.inventor.Inventor(
'Albert Einstein', 'German'))").getValue(societyContext);
parser.parseExpression(
"Members.add(new org.spring.samples.spel.inventor.Inventor('Albert Einstein', 'German'))")
.getValue(societyContext);
----
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes"]
----
val einstein = p.parseExpression(
"new org.spring.samples.spel.inventor.Inventor('Albert Einstein', 'German')")
val einstein = parser.parseExpression(
"new org.spring.samples.spel.inventor.Inventor('Albert Einstein', 'German')")
.getValue(Inventor::class.java)
// create new Inventor instance within the add() method of List
p.parseExpression(
"Members.add(new org.spring.samples.spel.inventor.Inventor('Albert Einstein', 'German'))")
parser.parseExpression(
"Members.add(new org.spring.samples.spel.inventor.Inventor('Albert Einstein', 'German'))")
.getValue(societyContext)
----
======
@@ -2,8 +2,12 @@
= Functions
You can extend SpEL by registering user-defined functions that can be called within
expressions by using the `#functionName(...)` syntax. Functions can be registered as
variables in `EvaluationContext` implementations via the `setVariable()` method.
expressions by using the `#functionName(...)` syntax, and like with standard method
invocations, xref:core/expressions/language-ref/varargs.adoc[varargs] are also supported
for function invocations.
Functions can be registered as _variables_ in `EvaluationContext` implementations via the
`setVariable()` method.
[TIP]
====
@@ -110,8 +114,9 @@ potentially more efficient use cases if the `MethodHandle` target and parameters
been fully bound prior to registration; however, partially bound handles are also
supported.
Consider the `String#formatted(String, Object...)` instance method, which produces a
message according to a template and a variable number of arguments.
Consider the `String#formatted(Object...)` instance method, which produces a message
according to a template and a variable number of arguments
(xref:core/expressions/language-ref/varargs.adoc[varargs]).
You can register and use the `formatted` method as a `MethodHandle`, as the following
example shows:
@@ -151,10 +156,10 @@ Kotlin::
----
======
As hinted above, binding a `MethodHandle` and registering the bound `MethodHandle` is also
supported. This is likely to be more performant if both the target and all the arguments
are bound. In that case no arguments are necessary in the SpEL expression, as the
following example shows:
As mentioned above, binding a `MethodHandle` and registering the bound `MethodHandle` is
also supported. This is likely to be more performant if both the target and all the
arguments are bound. In that case no arguments are necessary in the SpEL expression, as
the following example shows:
[tabs]
======
@@ -168,9 +173,10 @@ Java::
String template = "This is a %s message with %s words: <%s>";
Object varargs = new Object[] { "prerecorded", 3, "Oh Hello World!", "ignored" };
MethodHandle mh = MethodHandles.lookup().findVirtual(String.class, "formatted",
MethodType.methodType(String.class, Object[].class))
MethodType.methodType(String.class, Object[].class))
.bindTo(template)
.bindTo(varargs); //here we have to provide arguments in a single array binding
// Here we have to provide the arguments in a single array binding:
.bindTo(varargs);
context.setVariable("message", mh);
// evaluates to "This is a prerecorded message with 3 words: <Oh Hello World!>"
@@ -189,9 +195,10 @@ Kotlin::
val varargs = arrayOf("prerecorded", 3, "Oh Hello World!", "ignored")
val mh = MethodHandles.lookup().findVirtual(String::class.java, "formatted",
MethodType.methodType(String::class.java, Array<Any>::class.java))
MethodType.methodType(String::class.java, Array<Any>::class.java))
.bindTo(template)
.bindTo(varargs) //here we have to provide arguments in a single array binding
// Here we have to provide the arguments in a single array binding:
.bindTo(varargs)
context.setVariable("message", mh)
// evaluates to "This is a prerecorded message with 3 words: <Oh Hello World!>"
@@ -201,4 +208,3 @@ Kotlin::
======
@@ -1,9 +1,11 @@
[[expressions-methods]]
= Methods
You can invoke methods by using typical Java programming syntax. You can also invoke methods
on literals. Variable arguments are also supported. The following examples show how to
invoke methods:
You can invoke methods by using the typical Java programming syntax. You can also invoke
methods directly on literals such as strings or numbers.
xref:core/expressions/language-ref/varargs.adoc[Varargs] are supported as well.
The following examples show how to invoke methods.
[tabs]
======
@@ -0,0 +1,151 @@
[[expressions-varargs]]
= Varargs Invocations
The Spring Expression Language supports
https://docs.oracle.com/javase/8/docs/technotes/guides/language/varargs.html[varargs]
invocations for xref:core/expressions/language-ref/constructors.adoc[constructors],
xref:core/expressions/language-ref/methods.adoc[methods], and user-defined
xref:core/expressions/language-ref/functions.adoc[functions].
The following example shows how to invoke the `java.lang.String#formatted(Object...)`
_varargs_ method within an expression by supplying the variable argument list as separate
arguments (`'blue', 1`).
[tabs]
======
Java::
+
[source,java,indent=0,subs="verbatim,quotes"]
----
// evaluates to "blue is color #1"
String expression = "'%s is color #%d'.formatted('blue', 1)";
String message = parser.parseExpression(expression).getValue(String.class);
----
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes"]
----
// evaluates to "blue is color #1"
val expression = "'%s is color #%d'.formatted('blue', 1)"
val message = parser.parseExpression(expression).getValue(String::class.java)
----
======
A variable argument list can also be supplied as an array, as demonstrated in the
following example (`new Object[] {'blue', 1}`).
[tabs]
======
Java::
+
[source,java,indent=0,subs="verbatim,quotes"]
----
// evaluates to "blue is color #1"
String expression = "'%s is color #%d'.formatted(new Object[] {'blue', 1})";
String message = parser.parseExpression(expression).getValue(String.class);
----
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes"]
----
// evaluates to "blue is color #1"
val expression = "'%s is color #%d'.formatted(new Object[] {'blue', 1})"
val message = parser.parseExpression(expression).getValue(String::class.java)
----
======
As an alternative, a variable argument list can be supplied as a `java.util.List` for
example, as an xref:core/expressions/language-ref/inline-lists.adoc[inline list]
(`{'blue', 1}`). The following example shows how to do that.
[tabs]
======
Java::
+
[source,java,indent=0,subs="verbatim,quotes"]
----
// evaluates to "blue is color #1"
String expression = "'%s is color #%d'.formatted({'blue', 1})";
String message = parser.parseExpression(expression).getValue(String.class);
----
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes"]
----
// evaluates to "blue is color #1"
val expression = "'%s is color #%d'.formatted({'blue', 1})"
val message = parser.parseExpression(expression).getValue(String::class.java)
----
======
[[expressions-varargs-type-conversion]]
== Varargs Type Conversion
In contrast to the standard support for varargs invocations in Java,
xref:core/expressions/evaluation.adoc#expressions-type-conversion[type conversion] may be
applied to the individual arguments when invoking varargs constructors, methods, or
functions in SpEL.
For example, if we have registered a custom
xref:core/expressions/language-ref/functions.adoc[function] in the `EvaluationContext`
under the name `#reverseStrings` for a method with the signature
`String reverseStrings(String... strings)`, we can invoke that function within a SpEL
expression with any argument that can be converted to a `String`, as demonstrated in the
following example.
[tabs]
======
Java::
+
[source,java,indent=0,subs="verbatim,quotes"]
----
// evaluates to "3.0, 2.0, 1, SpEL"
String expression = "#reverseStrings('SpEL', 1, 10F / 5, 3.0000)";
String message = parser.parseExpression(expression)
.getValue(evaluationContext, String.class);
----
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes"]
----
// evaluates to "3.0, 2.0, 1, SpEL"
val expression = "#reverseStrings('SpEL', 1, 10F / 5, 3.0000)"
val message = parser.parseExpression(expression)
.getValue(evaluationContext, String::class.java)
----
======
Similarly, any array whose component type is a subtype of the required varargs type can
be supplied as the variable argument list for a varargs invocation. For example, a
`String[]` array can be supplied to a varargs invocation that accepts an `Object...`
argument list.
The following listing demonstrates that we can supply a `String[]` array to the
`java.lang.String#formatted(Object...)` _varargs_ method. It also highlights that `1`
will be automatically converted to `"1"`.
[tabs]
======
Java::
+
[source,java,indent=0,subs="verbatim,quotes"]
----
// evaluates to "blue is color #1"
String expression = "'%s is color #%s'.formatted(new String[] {'blue', 1})";
String message = parser.parseExpression(expression).getValue(String.class);
----
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes"]
----
// evaluates to "blue is color #1"
val expression = "'%s is color #%s'.formatted(new String[] {'blue', 1})"
val message = parser.parseExpression(expression).getValue(String::class.java)
----
======
@@ -6,7 +6,7 @@ the same way as Spring's integration does for the JDBC API.
JMS can be roughly divided into two areas of functionality, namely the production and
consumption of messages. The `JmsTemplate` class is used for message production and
synchronous message reception. For asynchronous reception similar to Jakarta EE's
synchronous message receipt. For asynchronous receipt similar to Jakarta EE's
message-driven bean style, Spring provides a number of message-listener containers that
you can use to create Message-Driven POJOs (MDPs). Spring also provides a declarative way
to create message listeners.
@@ -5,7 +5,7 @@ This describes how to receive messages with JMS in Spring.
[[jms-receiving-sync]]
== Synchronous Reception
== Synchronous Receipt
While JMS is typically associated with asynchronous processing, you can
consume messages synchronously. The overloaded `receive(..)` methods provide this
@@ -16,11 +16,11 @@ the receiver should wait before giving up waiting for a message.
[[jms-receiving-async]]
== Asynchronous reception: Message-Driven POJOs
== Asynchronous Receipt: Message-Driven POJOs
NOTE: Spring also supports annotated-listener endpoints through the use of the `@JmsListener`
annotation and provides an open infrastructure to register endpoints programmatically.
This is, by far, the most convenient way to setup an asynchronous receiver.
annotation and provides open infrastructure to register endpoints programmatically.
This is, by far, the most convenient way to set up an asynchronous receiver.
See xref:integration/jms/annotated.adoc#jms-annotated-support[Enable Listener Endpoint Annotations] for more details.
In a fashion similar to a Message-Driven Bean (MDB) in the EJB world, the Message-Driven
@@ -154,7 +154,7 @@ listener container.
You can activate local resource transactions through the `sessionTransacted` flag
on the listener container definition. Each message listener invocation then operates
within an active JMS transaction, with message reception rolled back in case of listener
within an active JMS transaction, with message receipt rolled back in case of listener
execution failure. Sending a response message (through `SessionAwareMessageListener`) is
part of the same local transaction, but any other resource operations (such as
database access) operate independently. This usually requires duplicate message
@@ -173,7 +173,7 @@ To configure a message listener container for XA transaction participation, you
to configure a `JtaTransactionManager` (which, by default, delegates to the Jakarta EE
server's transaction subsystem). Note that the underlying JMS `ConnectionFactory` needs to
be XA-capable and properly registered with your JTA transaction coordinator. (Check your
Jakarta EE server's configuration of JNDI resources.) This lets message reception as well
Jakarta EE server's configuration of JNDI resources.) This lets message receipt as well
as (for example) database access be part of the same transaction (with unified commit
semantics, at the expense of XA transaction log overhead).
@@ -167,13 +167,15 @@ operations that do not refer to a specific destination.
One of the most common uses of JMS messages in the EJB world is to drive message-driven
beans (MDBs). Spring offers a solution to create message-driven POJOs (MDPs) in a way
that does not tie a user to an EJB container. (See xref:integration/jms/receiving.adoc#jms-receiving-async[Asynchronous reception: Message-Driven POJOs] for detailed
coverage of Spring's MDP support.) Since Spring Framework 4.1, endpoint methods can be
annotated with `@JmsListener` -- see xref:integration/jms/annotated.adoc[Annotation-driven Listener Endpoints] for more details.
that does not tie a user to an EJB container. (See
xref:integration/jms/receiving.adoc#jms-receiving-async[Asynchronous Receipt: Message-Driven POJOs]
for detailed coverage of Spring's MDP support.) Endpoint methods can be annotated with
`@JmsListener` -- see xref:integration/jms/annotated.adoc[Annotation-driven Listener Endpoints]
for more details.
A message listener container is used to receive messages from a JMS message queue and
drive the `MessageListener` that is injected into it. The listener container is
responsible for all threading of message reception and dispatches into the listener for
responsible for all threading of message receipt and dispatches into the listener for
processing. A message listener container is the intermediary between an MDP and a
messaging provider and takes care of registering to receive messages, participating in
transactions, resource acquisition and release, exception conversion, and so on. This
@@ -227,7 +229,7 @@ the JMS provider, advanced functionality (such as participation in externally ma
transactions), and compatibility with Jakarta EE environments.
You can customize the cache level of the container. Note that, when no caching is enabled,
a new connection and a new session is created for each message reception. Combining this
a new connection and a new session is created for each message receipt. Combining this
with a non-durable subscription with high loads may lead to message loss. Make sure to
use a proper cache level in such a case.
@@ -246,7 +248,7 @@ in the form of a business entity existence check or a protocol table check.
Any such arrangements are significantly more efficient than the alternative:
wrapping your entire processing with an XA transaction (through configuring your
`DefaultMessageListenerContainer` with an `JtaTransactionManager`) to cover the
reception of the JMS message as well as the execution of the business logic in your
receipt of the JMS message as well as the execution of the business logic in your
message listener (including database operations, etc.).
IMPORTANT: The default `AUTO_ACKNOWLEDGE` mode does not provide proper reliability guarantees.
@@ -37,7 +37,7 @@ As outlined xref:integration/observability.adoc[at the beginning of this section
|Processing time for an execution of a `@Scheduled` task
|===
NOTE: Observations are using Micrometer's official naming convention, but Metrics names will be automatically converted
NOTE: Observations use Micrometer's official naming convention, but Metrics names will be automatically converted
{micrometer-docs}/concepts/naming.html[to the format preferred by the monitoring system backend]
(Prometheus, Atlas, Graphite, InfluxDB...).
@@ -97,7 +97,7 @@ This can be done by declaring a `SchedulingConfigurer` bean that sets the observ
include-code::./ObservationSchedulingConfigurer[]
It is using the `org.springframework.scheduling.support.DefaultScheduledTaskObservationConvention` by default, backed by the `ScheduledTaskObservationContext`.
It uses the `org.springframework.scheduling.support.DefaultScheduledTaskObservationConvention` by default, backed by the `ScheduledTaskObservationContext`.
You can configure a custom implementation on the `ObservationRegistry` directly.
During the execution of the scheduled method, the current observation is restored in the `ThreadLocal` context or the Reactor context (if the scheduled method returns a `Mono` or `Flux` type).
@@ -107,7 +107,7 @@ By default, the following `KeyValues` are created:
[cols="a,a"]
|===
|Name | Description
|`code.function` _(required)_|Name of Java `Method` that is scheduled for execution.
|`code.function` _(required)_|Name of the Java `Method` that is scheduled for execution.
|`code.namespace` _(required)_|Canonical name of the class of the bean instance that holds the scheduled method, or `"ANONYMOUS"` for anonymous classes.
|`error` _(required)_|Class name of the exception thrown during the execution, or `"none"` if no exception happened.
|`exception` _(deprecated)_|Duplicates the `error` key and might be removed in the future.
@@ -126,7 +126,7 @@ This instrumentation will create 2 types of observations:
* `"jms.message.publish"` when a JMS message is sent to the broker, typically with `JmsTemplate`.
* `"jms.message.process"` when a JMS message is processed by the application, typically with a `MessageListener` or a `@JmsListener` annotated method.
NOTE: currently there is no instrumentation for `"jms.message.receive"` observations as there is little value in measuring the time spent waiting for the reception of a message.
NOTE: Currently there is no instrumentation for `"jms.message.receive"` observations as there is little value in measuring the time spent waiting for the receipt of a message.
Such an integration would typically instrument `MessageConsumer#receive` method calls. But once those return, the processing time is not measured and the trace scope cannot be propagated to the application.
By default, both observations share the same set of possible `KeyValues`:
@@ -138,7 +138,7 @@ By default, both observations share the same set of possible `KeyValues`:
|`error` |Class name of the exception thrown during the messaging operation (or "none").
|`exception` _(deprecated)_|Duplicates the `error` key and might be removed in the future.
|`messaging.destination.temporary` _(required)_|Whether the destination is a `TemporaryQueue` or `TemporaryTopic` (values: `"true"` or `"false"`).
|`messaging.operation` _(required)_|Name of JMS operation being performed (values: `"publish"` or `"process"`).
|`messaging.operation` _(required)_|Name of the JMS operation being performed (values: `"publish"` or `"process"`).
|===
.High cardinality Keys
@@ -146,7 +146,7 @@ By default, both observations share the same set of possible `KeyValues`:
|===
|Name | Description
|`messaging.message.conversation_id` |The correlation ID of the JMS message.
|`messaging.destination.name` |The name of destination the current message was sent to.
|`messaging.destination.name` |The name of the destination the current message was sent to.
|`messaging.message.id` |Value used by the messaging system as an identifier for the message.
|===
@@ -213,7 +213,7 @@ By default, the following `KeyValues` are created:
|Name | Description
|`error` _(required)_|Class name of the exception thrown during the exchange, or `"none"` if no exception happened.
|`exception` _(deprecated)_|Duplicates the `error` key and might be removed in the future.
|`method` _(required)_|Name of HTTP request method or `"none"` if not a well-known method.
|`method` _(required)_|Name of the HTTP request method or `"none"` if not a well-known method.
|`outcome` _(required)_|Outcome of the HTTP server exchange.
|`status` _(required)_|HTTP response raw status code, or `"UNKNOWN"` if no response was created.
|`uri` _(required)_|URI pattern for the matching handler if available, falling back to `REDIRECTION` for 3xx responses, `NOT_FOUND` for 404 responses, `root` for requests with no path info, and `UNKNOWN` for all other requests.
@@ -235,10 +235,10 @@ This can be done on the `WebHttpHandlerBuilder`, as follows:
include-code::./HttpHandlerConfiguration[]
It is using the `org.springframework.http.server.reactive.observation.DefaultServerRequestObservationConvention` by default, backed by the `ServerRequestObservationContext`.
It uses the `org.springframework.http.server.reactive.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 an application Controller.
Typically, all exceptions handled by Spring WebFlux's `@ExceptionHandler` and <<web.adoc#webflux-ann-rest-exceptions,`ProblemDetail` support>> will not be recorded with the observation.
Typically, all exceptions handled by Spring WebFlux's `@ExceptionHandler` and xref:web/webflux/ann-rest-exceptions.adoc[`ProblemDetail` support] will not be recorded with the observation.
You can, at any point during request processing, set the error field on the `ObservationContext` yourself:
include-code::./UserController[]
@@ -251,7 +251,7 @@ By default, the following `KeyValues` are created:
|Name | Description
|`error` _(required)_|Class name of the exception thrown during the exchange, or `"none"` if no exception happened.
|`exception` _(deprecated)_|Duplicates the `error` key and might be removed in the future.
|`method` _(required)_|Name of HTTP request method or `"none"` if not a well-known method.
|`method` _(required)_|Name of the HTTP request method or `"none"` if not a well-known method.
|`outcome` _(required)_|Outcome of the HTTP server exchange.
|`status` _(required)_|HTTP response raw status code, or `"UNKNOWN"` if no response was created.
|`uri` _(required)_|URI pattern for the matching handler if available, falling back to `REDIRECTION` for 3xx responses, `NOT_FOUND` for 404 responses, `root` for requests with no path info, and `UNKNOWN` for all other requests.
@@ -270,6 +270,7 @@ By default, the following `KeyValues` are created:
== HTTP Client Instrumentation
HTTP client exchange observations are created with the name `"http.client.requests"` for blocking and reactive clients.
This observation measures the entire HTTP request/response exchange, from connection establishment up to body deserialization.
Unlike their server counterparts, the instrumentation is implemented directly in the client so the only required step is to configure an `ObservationRegistry` on the client.
[[observability.http-client.resttemplate]]
@@ -284,8 +285,8 @@ Instrumentation uses the `org.springframework.http.client.observation.ClientRequ
[cols="a,a"]
|===
|Name | Description
|`method` _(required)_|Name of HTTP request method or `"none"` if not a well-known method.
|`uri` _(required)_|URI template used for HTTP request, or `"none"` if none was provided. Only the path part of the URI is considered.
|`method` _(required)_|Name of the HTTP request method or `"none"` if not a well-known method.
|`uri` _(required)_|URI template used for HTTP request, or `"none"` if none was provided. The protocol, host and port part of the URI are not considered.
|`client.name` _(required)_|Client name derived from the request URI host.
|`status` _(required)_|HTTP response raw status code, or `"IO_ERROR"` in case of `IOException`, or `"CLIENT_ERROR"` if no response was received.
|`outcome` _(required)_|Outcome of the HTTP client exchange.
@@ -312,8 +313,8 @@ Instrumentation uses the `org.springframework.http.client.observation.ClientRequ
[cols="a,a"]
|===
|Name | Description
|`method` _(required)_|Name of HTTP request method or `"none"` if the request could not be created.
|`uri` _(required)_|URI template used for HTTP request, or `"none"` if none was provided. Only the path part of the URI is considered.
|`method` _(required)_|Name of the HTTP request method or `"none"` if the request could not be created.
|`uri` _(required)_|URI template used for HTTP request, or `"none"` if none was provided. The protocol, host and port part of the URI are not considered.
|`client.name` _(required)_|Client name derived from the request URI host.
|`status` _(required)_|HTTP response raw status code, or `"IO_ERROR"` in case of `IOException`, or `"CLIENT_ERROR"` if no response was received.
|`outcome` _(required)_|Outcome of the HTTP client exchange.
@@ -332,7 +333,7 @@ Instrumentation uses the `org.springframework.http.client.observation.ClientRequ
[[observability.http-client.webclient]]
=== WebClient
Applications must configure an `ObservationRegistry` on the `WebClient` builder to enable the instrumentation; without that, observations are "no-ops".
Applications must configure an `ObservationRegistry` on the `WebClient.Builder` to enable the instrumentation; without that, observations are "no-ops".
Spring Boot will auto-configure `WebClient.Builder` beans with the observation registry already set.
Instrumentation uses the `org.springframework.web.reactive.function.client.ClientRequestObservationConvention` by default, backed by the `ClientRequestObservationContext`.
@@ -341,8 +342,8 @@ Instrumentation uses the `org.springframework.web.reactive.function.client.Clien
[cols="a,a"]
|===
|Name | Description
|`method` _(required)_|Name of HTTP request method or `"none"` if not a well-known method.
|`uri` _(required)_|URI template used for HTTP request, or `"none"` if none was provided. Only the path part of the URI is considered.
|`method` _(required)_|Name of the HTTP request method or `"none"` if not a well-known method.
|`uri` _(required)_|URI template used for HTTP request, or `"none"` if none was provided. The protocol, host and port part of the URI are not considered.
|`client.name` _(required)_|Client name derived from the request URI host.
|`status` _(required)_|HTTP response raw status code, or `"IO_ERROR"` in case of `IOException`, or `"CLIENT_ERROR"` if no response was received.
|`outcome` _(required)_|Outcome of the HTTP client exchange.
@@ -938,10 +938,10 @@ method parameters:
| Dynamically set the HTTP method for the request, overriding the annotation's `method` attribute
| `@RequestHeader`
| Add a request header or multiple headers. The argument may be a `Map<String, ?>` or
`MultiValueMap<String, ?>` with multiple headers, a `Collection<?>` of values, or an
individual value. Type conversion is supported for non-String values. This overrides
the annotation's `headers` attribute.
| Add a request header or multiple headers. The argument may be a single value,
a `Collection<?>` of values, `Map<String, ?>`,`MultiValueMap<String, ?>`.
Type conversion is supported for non-String values. Header values are added and
do not override already added header values.
| `@PathVariable`
| Add a variable for expand a placeholder in the request URL. The argument may be a
@@ -14,16 +14,13 @@ For example, `@Autowired lateinit var thing: Thing` implies that a bean
of type `Thing` must be registered in the application context, while `@Autowired lateinit var thing: Thing?`
does not raise an error if such a bean does not exist.
Following the same principle, `@Bean fun play(toy: Toy, car: Car?) = Baz(toy, Car)` implies
Following the same principle, `@Bean fun play(toy: Toy, car: Car?) = Baz(toy, car)` implies
that a bean of type `Toy` must be registered in the application context, while a bean of
type `Car` may or may not exist. The same behavior applies to autowired constructor parameters.
NOTE: If you use bean validation on classes with properties or a primary constructor
parameters, you may need to use
with parameters, you may need to use
{kotlin-docs}/annotations.html#annotation-use-site-targets[annotation use-site targets],
such as `@field:NotNull` or `@get:Size(min=5, max=15)`, as described in
{stackoverflow-site}/a/35853200/1092077[this Stack Overflow response].
@@ -1,38 +1,31 @@
[[spring-testing-annotation-beanoverriding-mockitobean]]
= `@MockitoBean` and `@MockitoSpyBean`
`@MockitoBean` and `@MockitoSpyBean` are used on fields in test classes to override beans
in the test's `ApplicationContext` with a Mockito _mock_ or _spy_, respectively. In the
latter case, an early instance of the original bean is captured and wrapped by the spy.
`@MockitoBean` and `@MockitoSpyBean` are used on non-static fields in test classes to
override beans in the test's `ApplicationContext` with a Mockito _mock_ or _spy_,
respectively. In the latter case, an early instance of the original bean is captured and
wrapped by the spy.
By default, the annotated field's type is used to search for candidate beans to override.
If multiple candidates match, `@Qualifier` can be provided to narrow the candidate to
override. Alternatively, a candidate whose bean name matches the name of the field will
match.
When using `@MockitoBean`, a new bean will be created if a corresponding bean does not
exist. However, if you would like for the test to fail when a corresponding bean does not
exist, you can set the `enforceOverride` attribute to `true` for example,
`@MockitoBean(enforceOverride = true)`.
To use a by-name override rather than a by-type override, specify the `name` attribute
of the annotation.
[WARNING]
====
Qualifiers, including the name of the field, are used to determine if a separate
`ApplicationContext` needs to be created. If you are using this feature to mock or spy
the same bean in several tests, make sure to name the field consistently to avoid
the same bean in several test classes, make sure to name the field consistently to avoid
creating unnecessary contexts.
====
Each annotation also defines Mockito-specific attributes to fine-tune the mocking details.
Each annotation also defines Mockito-specific attributes to fine-tune the mocking behavior.
By default, the `@MockitoBean` annotation uses the `REPLACE_OR_CREATE`
The `@MockitoBean` annotation uses the `REPLACE_OR_CREATE`
xref:testing/testcontext-framework/bean-overriding.adoc#testcontext-bean-overriding-custom[strategy for test bean overriding].
If no existing bean matches, a new bean is created on the fly. As mentioned previously,
you can switch to the `REPLACE` strategy by setting the `enforceOverride` attribute to
`true`.
If no existing bean matches, a new bean is created on the fly. However, you can switch to
the `REPLACE` strategy by setting the `enforceOverride` attribute to `true`. See the
following section for an example.
The `@MockitoSpyBean` annotation uses the `WRAP`
xref:testing/testcontext-framework/bean-overriding.adoc#testcontext-bean-overriding-custom[strategy],
@@ -51,6 +44,26 @@ When using `@MockitoSpyBean` to create a spy for a `FactoryBean`, a spy will be
for the object created by the `FactoryBean`, not for the `FactoryBean` itself.
====
[NOTE]
====
There are no restrictions on the visibility of `@MockitoBean` and `@MockitoSpyBean`
fields.
Such fields can therefore be `public`, `protected`, package-private (default visibility),
or `private` depending on the needs or coding practices of the project.
====
[[spring-testing-annotation-beanoverriding-mockitobean-examples]]
== `@MockitoBean` Examples
When using `@MockitoBean`, a new bean will be created if a corresponding bean does not
exist. However, if you would like for the test to fail when a corresponding bean does not
exist, you can set the `enforceOverride` attribute to `true` for example,
`@MockitoBean(enforceOverride = true)`.
To use a by-name override rather than a by-type override, specify the `name` (or `value`)
attribute of the annotation.
The following example shows how to use the default behavior of the `@MockitoBean` annotation:
[tabs]
@@ -59,11 +72,13 @@ Java::
+
[source,java,indent=0,subs="verbatim,quotes"]
----
class OverrideBeanTests {
@MockitoBean // <1>
private CustomService customService;
@SpringJUnitConfig(TestConfig.class)
class BeanOverrideTests {
// test case body...
@MockitoBean // <1>
CustomService customService;
// tests...
}
----
<1> Replace the bean with type `CustomService` with a Mockito `mock`.
@@ -72,8 +87,8 @@ Java::
In the example above, we are creating a mock for `CustomService`. If more than one bean
of that type exists, the bean named `customService` is considered. Otherwise, the test
will fail, and you will need to provide a qualifier of some sort to identify which of the
`CustomService` beans you want to override. If no such bean exists, a bean definition
will be created with an auto-generated bean name.
`CustomService` beans you want to override. If no such bean exists, a bean will be
created with an auto-generated bean name.
The following example uses a by-name lookup, rather than a by-type lookup:
@@ -83,20 +98,43 @@ Java::
+
[source,java,indent=0,subs="verbatim,quotes"]
----
class OverrideBeanTests {
@MockitoBean("service") // <1>
private CustomService customService;
@SpringJUnitConfig(TestConfig.class)
class BeanOverrideTests {
// test case body...
@MockitoBean("service") // <1>
CustomService customService;
// tests...
}
----
<1> Replace the bean named `service` with a Mockito `mock`.
======
If no bean definition named `service` exists, one is created.
If no bean named `service` exists, one is created.
The following example shows how to use the default behavior of the `@MockitoSpyBean` annotation:
`@MockitoBean` can also be used at the type level:
- on a test class or any superclass or implemented interface in the type hierarchy above
the test class
- on an enclosing class for a `@Nested` test class or on any class or interface in the
type hierarchy or enclosing class hierarchy above the `@Nested` test class
When `@MockitoBean` is declared at the type level, the type of bean (or beans) to mock
must be supplied via the `types` attribute for example,
`@MockitoBean(types = {OrderService.class, UserService.class})`. If multiple candidates
exist in the application context, you can explicitly specify a bean name to mock by
setting the `name` attribute. Note, however, that the `types` attribute must contain a
single type if an explicit bean `name` is configured for example,
`@MockitoBean(name = "ps1", types = PrintingService.class)`.
To support reuse of mock configuration, `@MockitoBean` may be used as a meta-annotation
to create custom _composed annotations_ — for example, to define common mock
configuration in a single annotation that can be reused across a test suite.
`@MockitoBean` can also be used as a repeatable annotation at the type level — for
example, to mock several beans by name.
The following `@SharedMocks` annotation registers two mocks by-type and one mock by-name.
[tabs]
======
@@ -104,11 +142,70 @@ Java::
+
[source,java,indent=0,subs="verbatim,quotes"]
----
class OverrideBeanTests {
@MockitoSpyBean // <1>
private CustomService customService;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@MockitoBean(types = {OrderService.class, UserService.class}) // <1>
@MockitoBean(name = "ps1", types = PrintingService.class) // <2>
public @interface SharedMocks {
}
----
<1> Register `OrderService` and `UserService` mocks by-type.
<2> Register `PrintingService` mock by-name.
======
// test case body...
The following demonstrates how `@SharedMocks` can be used on a test class.
[tabs]
======
Java::
+
[source,java,indent=0,subs="verbatim,quotes"]
----
@SpringJUnitConfig(TestConfig.class)
@SharedMocks // <1>
class BeanOverrideTests {
@Autowired OrderService orderService; // <2>
@Autowired UserService userService; // <2>
@Autowired PrintingService ps1; // <2>
// Inject other components that rely on the mocks.
@Test
void testThatDependsOnMocks() {
// ...
}
}
----
<1> Register common mocks via the custom `@SharedMocks` annotation.
<2> Optionally inject mocks to _stub_ or _verify_ them.
======
TIP: The mocks can also be injected into `@Configuration` classes or other test-related
components in the `ApplicationContext` in order to configure them with Mockito's stubbing
APIs.
[[spring-testing-annotation-beanoverriding-mockitospybean-examples]]
== `@MockitoSpyBean` Examples
The following example shows how to use the default behavior of the `@MockitoSpyBean`
annotation:
[tabs]
======
Java::
+
[source,java,indent=0,subs="verbatim,quotes"]
----
@SpringJUnitConfig(TestConfig.class)
class BeanOverrideTests {
@MockitoSpyBean // <1>
CustomService customService;
// tests...
}
----
<1> Wrap the bean with type `CustomService` with a Mockito `spy`.
@@ -127,12 +224,13 @@ Java::
+
[source,java,indent=0,subs="verbatim,quotes"]
----
class OverrideBeanTests {
@SpringJUnitConfig(TestConfig.class)
class BeanOverrideTests {
@MockitoSpyBean("service") // <1>
private CustomService customService;
// test case body...
CustomService customService;
// tests...
}
----
<1> Wrap the bean named `service` with a Mockito `spy`.
@@ -1,8 +1,8 @@
[[spring-testing-annotation-beanoverriding-testbean]]
= `@TestBean`
`@TestBean` is used on a field in a test class to override a specific bean in the test's
`ApplicationContext` with an instance provided by a factory method.
`@TestBean` is used on a non-static field in a test class to override a specific bean in
the test's `ApplicationContext` with an instance provided by a factory method.
The associated factory method name is derived from the annotated field's name, or the
bean name if specified. The factory method must be `static`, accept no arguments, and
@@ -30,6 +30,14 @@ same bean in several tests, make sure to name the field consistently to avoid cr
unnecessary contexts.
====
[NOTE]
====
There are no restrictions on the visibility of `@TestBean` fields or factory methods.
Such fields and methods can therefore be `public`, `protected`, package-private (default
visibility), or `private` depending on the needs or coding practices of the project.
====
The following example shows how to use the default behavior of the `@TestBean` annotation:
[tabs]
@@ -40,11 +48,11 @@ Java::
----
class OverrideBeanTests {
@TestBean // <1>
private CustomService customService;
CustomService customService;
// test case body...
private static CustomService customService() { // <2>
static CustomService customService() { // <2>
return new MyFakeCustomService();
}
}
@@ -68,11 +76,11 @@ Java::
----
class OverrideBeanTests {
@TestBean(name = "service", methodName = "createCustomService") // <1>
private CustomService customService;
CustomService customService;
// test case body...
private static CustomService createCustomService() { // <2>
static CustomService createCustomService() { // <2>
return new MyFakeCustomService();
}
}
@@ -84,8 +92,10 @@ Java::
[TIP]
====
Spring searches for the factory method to invoke in the test class, in the test class
hierarchy, and in the enclosing class hierarchy for a `@Nested` test class.
To locate the factory method to invoke, Spring searches in the class in which the
`@TestBean` field is declared, in one of its superclasses, or in any implemented
interfaces. If the `@TestBean` field is declared in a `@Nested` test class, the enclosing
class hierarchy will also be searched.
Alternatively, a factory method in an external class can be referenced via its
fully-qualified method name following the syntax `<fully-qualified class name>#<method name>`
@@ -2,7 +2,8 @@
= Bean Overriding in Tests
Bean overriding in tests refers to the ability to override specific beans in the
`ApplicationContext` for a test class, by annotating one or more fields in the test class.
`ApplicationContext` for a test class, by annotating one or more non-static fields in the
test class.
NOTE: This feature is intended as a less risky alternative to the practice of registering
a bean via `@Bean` with the `DefaultListableBeanFactory`
@@ -41,9 +42,10 @@ The `spring-test` module registers implementations of the latter two
{spring-framework-code}/spring-test/src/main/resources/META-INF/spring.factories[`META-INF/spring.factories`
properties file].
The bean overriding infrastructure searches in test classes for any field meta-annotated
with `@BeanOverride` and instantiates the corresponding `BeanOverrideProcessor` which is
responsible for creating an appropriate `BeanOverrideHandler`.
The bean overriding infrastructure searches in test classes for any non-static field that
is meta-annotated with `@BeanOverride` and instantiates the corresponding
`BeanOverrideProcessor` which is responsible for creating an appropriate
`BeanOverrideHandler`.
The internal `BeanOverrideBeanFactoryPostProcessor` then uses bean override handlers to
alter the test's `ApplicationContext` by creating, replacing, or wrapping beans as
@@ -127,7 +127,7 @@ Kotlin::
======
For Spring MVC, use the following where the Spring `ApplicationContext` is passed to
{spring-framework-api}/test/web/servlet/setup/MockMvcBuilders.html#webAppContextSetup-org.springframework.web.context.WebApplicationContext-[MockMvcBuilders.webAppContextSetup]
{spring-framework-api}/test/web/servlet/setup/MockMvcBuilders.html#webAppContextSetup(org.springframework.web.context.WebApplicationContext)[MockMvcBuilders.webAppContextSetup]
to create a xref:testing/mockmvc.adoc[MockMvc] instance to handle
requests:
@@ -193,7 +193,7 @@ Kotlin::
[[webtestclient-fn-config]]
=== Bind to Router Function
This setup allows you to test <<web-reactive.adoc#webflux-fn, functional endpoints>> via
This setup allows you to test xref:web/webflux-functional.adoc[functional endpoints] via
mock request and response objects, without a running server.
For WebFlux, use the following which delegates to `RouterFunctions.toWebHandler` to
@@ -1,5 +1,6 @@
[[webflux-cors]]
= CORS
[.small]#xref:web/webmvc-cors.adoc[See equivalent in the Servlet stack]#
Spring WebFlux lets you handle CORS (Cross-Origin Resource Sharing). This section
@@ -364,7 +365,7 @@ Kotlin::
You can apply CORS support through the built-in
{spring-framework-api}/web/cors/reactive/CorsWebFilter.html[`CorsWebFilter`], which is a
good fit with <<webflux-fn, functional endpoints>>.
good fit with xref:web/webflux-functional.adoc[functional endpoints].
NOTE: If you try to use the `CorsFilter` with Spring Security, keep in mind that Spring
Security has {docs-spring-security}/servlet/integrations/cors.html[built-in support] for
@@ -1,5 +1,6 @@
[[webflux-fn]]
= Functional Endpoints
[.small]#xref:web/webmvc-functional.adoc[See equivalent in the Servlet stack]#
Spring WebFlux includes WebFlux.fn, a lightweight functional programming model in which functions
@@ -1,5 +1,6 @@
[[webflux-websocket]]
= WebSockets
[.small]#xref:web/websocket.adoc[See equivalent in the Servlet stack]#
This part of the reference documentation covers support for reactive-stack WebSocket
@@ -605,9 +605,4 @@ For method parameters and returns values, generally, `@HttpExchange` supports a
subset of the method parameters that `@RequestMapping` does. Notably, it excludes any
server-side specific parameter types. For details, see the list for
xref:integration/rest-clients.adoc#rest-http-interface-method-parameters[@HttpExchange] and
xref:web/webflux/controller/ann-methods/arguments.adoc[@RequestMapping].
`@HttpExchange` also supports a `headers()` parameter which accepts `"name=value"`-like
pairs like in `@RequestMapping(headers={})` on the client side. On the server side,
this extends to the full syntax that
xref:#webflux-ann-requestmapping-params-and-headers[`@RequestMapping`] supports.
xref:web/webflux/controller/ann-methods/arguments.adoc[@RequestMapping].
@@ -101,7 +101,7 @@ On that foundation, Spring WebFlux provides a choice of two programming models:
from the `spring-web` module. Both Spring MVC and WebFlux controllers support reactive
(Reactor and RxJava) return types, and, as a result, it is not easy to tell them apart. One notable
difference is that WebFlux also supports reactive `@RequestBody` arguments.
* <<webflux-fn>>: Lambda-based, lightweight, and functional programming model. You can think of
* xref:web/webflux-functional.adoc[Functional Endpoints]: Lambda-based, lightweight, and functional programming model. You can think of
this as a small library or a set of utilities that an application can use to route and
handle requests. The big difference with annotated controllers is that the application
is in charge of request handling from start to finish versus declaring intent through
@@ -1,5 +1,6 @@
[[mvc-cors]]
= CORS
[.small]#xref:web/webflux-cors.adoc[See equivalent in the Reactive stack]#
Spring MVC lets you handle CORS (Cross-Origin Resource Sharing). This section
@@ -1,6 +1,7 @@
[[webmvc-fn]]
= Functional Endpoints
[.small]#<<web-reactive.adoc#webflux-fn, See equivalent in the Reactive stack>>#
[.small]#xref:web/webflux-functional.adoc[See equivalent in the Reactive stack]#
Spring Web MVC includes WebMvc.fn, a lightweight functional programming model in which functions
are used to route and handle requests and contracts are designed for immutability.
@@ -30,7 +30,7 @@ available through the `ServletRequest.getParameter{asterisk}()` family of method
[[forwarded-headers]]
[[filters-forwarded-headers]]
== Forwarded Headers
[.small]#xref:web/webflux/reactive-spring.adoc#webflux-forwarded-headers[See equivalent in the Reactive stack]#
@@ -1,6 +1,7 @@
[[websocket]]
= WebSockets
:page-section-summary-toc: 1
[.small]#xref:web/webflux-websocket.adoc[See equivalent in the Reactive stack]#
This part of the reference documentation covers support for Servlet stack, WebSocket
+13 -13
View File
@@ -7,21 +7,21 @@ javaPlatform {
}
dependencies {
api(platform("com.fasterxml.jackson:jackson-bom:2.18.1"))
api(platform("io.micrometer:micrometer-bom:1.14.0"))
api(platform("io.netty:netty-bom:4.1.115.Final"))
api(platform("com.fasterxml.jackson:jackson-bom:2.18.2"))
api(platform("io.micrometer:micrometer-bom:1.14.3"))
api(platform("io.netty:netty-bom:4.1.117.Final"))
api(platform("io.netty:netty5-bom:5.0.0.Alpha5"))
api(platform("io.projectreactor:reactor-bom:2024.0.0"))
api(platform("io.projectreactor:reactor-bom:2024.0.2"))
api(platform("io.rsocket:rsocket-bom:1.1.4"))
api(platform("org.apache.groovy:groovy-bom:4.0.24"))
api(platform("org.apache.logging.log4j:log4j-bom:2.21.1"))
api(platform("org.assertj:assertj-bom:3.26.3"))
api(platform("org.eclipse.jetty:jetty-bom:12.0.15"))
api(platform("org.eclipse.jetty.ee10:jetty-ee10-bom:12.0.15"))
api(platform("org.assertj:assertj-bom:3.27.2"))
api(platform("org.eclipse.jetty:jetty-bom:12.0.16"))
api(platform("org.eclipse.jetty.ee10:jetty-ee10-bom:12.0.16"))
api(platform("org.jetbrains.kotlinx:kotlinx-coroutines-bom:1.8.1"))
api(platform("org.jetbrains.kotlinx:kotlinx-serialization-bom:1.6.3"))
api(platform("org.junit:junit-bom:5.11.3"))
api(platform("org.mockito:mockito-bom:5.14.2"))
api(platform("org.junit:junit-bom:5.11.4"))
api(platform("org.mockito:mockito-bom:5.15.2"))
constraints {
api("com.fasterxml:aalto-xml:1.3.2")
@@ -31,7 +31,7 @@ dependencies {
api("com.google.code.findbugs:findbugs:3.0.1")
api("com.google.code.findbugs:jsr305:3.0.2")
api("com.google.code.gson:gson:2.11.0")
api("com.google.protobuf:protobuf-java-util:4.28.3")
api("com.google.protobuf:protobuf-java-util:4.29.3")
api("com.h2database:h2:2.3.232")
api("com.jayway.jsonpath:json-path:2.9.0")
api("com.oracle.database.jdbc:ojdbc11:21.9.0.0")
@@ -54,11 +54,11 @@ dependencies {
api("io.r2dbc:r2dbc-h2:1.0.0.RELEASE")
api("io.r2dbc:r2dbc-spi-test:1.0.0.RELEASE")
api("io.r2dbc:r2dbc-spi:1.0.0.RELEASE")
api("io.reactivex.rxjava3:rxjava:3.1.9")
api("io.reactivex.rxjava3:rxjava:3.1.10")
api("io.smallrye.reactive:mutiny:1.10.0")
api("io.undertow:undertow-core:2.3.18.Final")
api("io.undertow:undertow-servlet:2.3.17.Final")
api("io.undertow:undertow-websockets-jsr:2.3.17.Final")
api("io.undertow:undertow-servlet:2.3.18.Final")
api("io.undertow:undertow-websockets-jsr:2.3.18.Final")
api("io.vavr:vavr:0.10.4")
api("jakarta.activation:jakarta.activation-api:2.0.1")
api("jakarta.annotation:jakarta.annotation-api:2.0.0")
+1 -1
View File
@@ -1,4 +1,4 @@
version=6.2.0
version=6.2.2
org.gradle.caching=true
org.gradle.jvmargs=-Xmx2048m
+1 -1
View File
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
Vendored
+1 -2
View File
@@ -86,8 +86,7 @@ done
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
' "$PWD" ) || exit
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2008 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,11 +27,11 @@ package org.springframework.aop;
* <p>Some examples of valid methods would be:
*
* <pre class="code">public void afterThrowing(Exception ex)</pre>
* <pre class="code">public void afterThrowing(RemoteException)</pre>
* <pre class="code">public void afterThrowing(RemoteException ex)</pre>
* <pre class="code">public void afterThrowing(Method method, Object[] args, Object target, Exception ex)</pre>
* <pre class="code">public void afterThrowing(Method method, Object[] args, Object target, ServletException ex)</pre>
*
* The first three arguments are optional, and only useful if we want further
* <p>The first three arguments are optional, and only useful if we want further
* information about the joinpoint, as in AspectJ <b>after-throwing</b> advice.
*
* <p><b>Note:</b> If a throws-advice method throws an exception itself, it will
@@ -668,7 +668,8 @@ public class AdvisedSupport extends ProxyConfig implements Advised {
@Override
public boolean equals(@Nullable Object other) {
return (this == other || (other instanceof MethodCacheKey that && this.method == that.method));
return (this == other || (other instanceof MethodCacheKey that &&
(this.method == that.method || this.method.equals(that.method))));
}
@Override
@@ -60,11 +60,12 @@ public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
if (config.isOptimize() || config.isProxyTargetClass() || !config.hasUserSuppliedInterfaces()) {
Class<?> targetClass = config.getTargetClass();
if (targetClass == null) {
if (targetClass == null && config.getProxiedInterfaces().length == 0) {
throw new AopConfigException("TargetSource cannot determine target class: " +
"Either an interface or a target is required for proxy creation.");
}
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass) || ClassUtils.isLambdaClass(targetClass)) {
if (targetClass == null || targetClass.isInterface() ||
Proxy.isProxyClass(targetClass) || ClassUtils.isLambdaClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
return new ObjenesisCglibAopProxy(config);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2024 the original author or authors.
* Copyright 2002-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -99,7 +99,7 @@ abstract class AbstractProxyExceptionHandlingTests {
assertThat(throwableSeenByInterceptor).isSameAs(undeclaredCheckedException);
assertThat(throwableSeenByCaller)
.isInstanceOf(UndeclaredThrowableException.class)
.hasCauseReference(undeclaredCheckedException);
.cause().isSameAs(undeclaredCheckedException);
}
@Test
@@ -147,7 +147,7 @@ abstract class AbstractProxyExceptionHandlingTests {
invokeProxy();
assertThat(throwableSeenByCaller)
.isInstanceOf(UndeclaredThrowableException.class)
.hasCauseReference(undeclaredCheckedException);
.cause().isSameAs(undeclaredCheckedException);
}
@Test
@@ -340,6 +340,18 @@ class ProxyFactoryTests {
assertThat(AopProxyUtils.ultimateTargetClass(proxy)).isEqualTo(MyDate.class);
}
@Test
void proxyInterfaceInCaseOfIntroducedInterfaceOnly() {
ProxyFactory pf = new ProxyFactory();
pf.addInterface(TimeStamped.class);
TimestampIntroductionInterceptor ti = new TimestampIntroductionInterceptor(0L);
pf.addAdvisor(new DefaultIntroductionAdvisor(ti, TimeStamped.class));
Object proxy = pf.getProxy();
assertThat(AopUtils.isJdkDynamicProxy(proxy)).as("Proxy is a JDK proxy").isTrue();
assertThat(proxy).isInstanceOf(TimeStamped.class);
assertThat(AopProxyUtils.ultimateTargetClass(proxy)).isEqualTo(proxy.getClass());
}
@Test
void proxyInterfaceInCaseOfNonTargetInterface() {
ProxyFactory pf = new ProxyFactory();
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2024 the original author or authors.
* Copyright 2002-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -95,7 +95,7 @@ public abstract class BeanFactoryAnnotationUtils {
// Full qualifier matching supported.
return qualifiedBeanOfType(lbf, beanType, qualifier);
}
else if (beanFactory.containsBean(qualifier)) {
else if (beanFactory.containsBean(qualifier) && beanFactory.isTypeMatch(qualifier, beanType)) {
// Fallback: target bean at least found by bean name.
return beanFactory.getBean(qualifier, beanType);
}
@@ -110,16 +110,16 @@ public abstract class BeanFactoryAnnotationUtils {
/**
* Obtain a bean of type {@code T} from the given {@code BeanFactory} declaring a qualifier
* (for example, {@code <qualifier>} or {@code @Qualifier}) matching the given qualifier).
* @param bf the factory to get the target bean from
* @param beanFactory the factory to get the target bean from
* @param beanType the type of bean to retrieve
* @param qualifier the qualifier for selecting between multiple bean matches
* @return the matching bean of type {@code T} (never {@code null})
*/
private static <T> T qualifiedBeanOfType(ListableBeanFactory bf, Class<T> beanType, String qualifier) {
String[] candidateBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(bf, beanType);
private static <T> T qualifiedBeanOfType(ListableBeanFactory beanFactory, Class<T> beanType, String qualifier) {
String[] candidateBeans = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(beanFactory, beanType);
String matchingBean = null;
for (String beanName : candidateBeans) {
if (isQualifierMatch(qualifier::equals, beanName, bf)) {
if (isQualifierMatch(qualifier::equals, beanName, beanFactory)) {
if (matchingBean != null) {
throw new NoUniqueBeanDefinitionException(beanType, matchingBean, beanName);
}
@@ -127,11 +127,11 @@ public abstract class BeanFactoryAnnotationUtils {
}
}
if (matchingBean != null) {
return bf.getBean(matchingBean, beanType);
return beanFactory.getBean(matchingBean, beanType);
}
else if (bf.containsBean(qualifier)) {
else if (beanFactory.containsBean(qualifier) && beanFactory.isTypeMatch(qualifier, beanType)) {
// Fallback: target bean at least found by bean name - probably a manually registered singleton.
return bf.getBean(qualifier, beanType);
return beanFactory.getBean(qualifier, beanType);
}
else {
throw new NoSuchBeanDefinitionException(qualifier, "No matching " + beanType.getSimpleName() +
@@ -123,7 +123,7 @@ class DefaultBeanRegistrationCodeFragments implements BeanRegistrationCodeFragme
CodeBlock.Builder code = CodeBlock.builder();
RootBeanDefinition mbd = this.registeredBean.getMergedBeanDefinition();
Class<?> beanClass = (mbd.hasBeanClass() ? mbd.getBeanClass() : null);
Class<?> beanClass = (mbd.hasBeanClass() ? ClassUtils.getUserClass(mbd.getBeanClass()) : null);
CodeBlock beanClassCode = generateBeanClassCode(
beanRegistrationCode.getClassName().packageName(),
(beanClass != null ? beanClass : beanType.toClass()));
@@ -156,91 +156,96 @@ public class InstanceSupplierCodeGenerator {
}
private CodeBlock generateCodeForConstructor(RegisteredBean registeredBean, Constructor<?> constructor) {
String beanName = registeredBean.getBeanName();
Class<?> beanClass = registeredBean.getBeanClass();
ConstructorDescriptor descriptor = new ConstructorDescriptor(
registeredBean.getBeanName(), constructor, registeredBean.getBeanClass());
if (KotlinDetector.isKotlinReflectPresent() && KotlinDelegate.hasConstructorWithOptionalParameter(beanClass)) {
return generateCodeForInaccessibleConstructor(beanName, constructor,
hints -> hints.registerType(beanClass, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS));
Class<?> publicType = descriptor.publicType();
if (KotlinDetector.isKotlinReflectPresent() && KotlinDelegate.hasConstructorWithOptionalParameter(publicType)) {
return generateCodeForInaccessibleConstructor(descriptor,
hints -> hints.registerType(publicType, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS));
}
if (!isVisible(constructor, constructor.getDeclaringClass())) {
return generateCodeForInaccessibleConstructor(beanName, constructor,
return generateCodeForInaccessibleConstructor(descriptor,
hints -> hints.registerConstructor(constructor, ExecutableMode.INVOKE));
}
return generateCodeForAccessibleConstructor(beanName, constructor);
return generateCodeForAccessibleConstructor(descriptor);
}
private CodeBlock generateCodeForAccessibleConstructor(String beanName, Constructor<?> constructor) {
private CodeBlock generateCodeForAccessibleConstructor(ConstructorDescriptor descriptor) {
Constructor<?> constructor = descriptor.constructor();
this.generationContext.getRuntimeHints().reflection().registerConstructor(
constructor, ExecutableMode.INTROSPECT);
if (constructor.getParameterCount() == 0) {
if (!this.allowDirectSupplierShortcut) {
return CodeBlock.of("$T.using($T::new)", InstanceSupplier.class, constructor.getDeclaringClass());
return CodeBlock.of("$T.using($T::new)", InstanceSupplier.class, descriptor.actualType());
}
if (!isThrowingCheckedException(constructor)) {
return CodeBlock.of("$T::new", constructor.getDeclaringClass());
return CodeBlock.of("$T::new", descriptor.actualType());
}
return CodeBlock.of("$T.of($T::new)", ThrowingSupplier.class, constructor.getDeclaringClass());
return CodeBlock.of("$T.of($T::new)", ThrowingSupplier.class, descriptor.actualType());
}
GeneratedMethod generatedMethod = generateGetInstanceSupplierMethod(method ->
buildGetInstanceMethodForConstructor(method, beanName, constructor, PRIVATE_STATIC));
buildGetInstanceMethodForConstructor(method, descriptor, PRIVATE_STATIC));
return generateReturnStatement(generatedMethod);
}
private CodeBlock generateCodeForInaccessibleConstructor(String beanName,
Constructor<?> constructor, Consumer<ReflectionHints> hints) {
private CodeBlock generateCodeForInaccessibleConstructor(ConstructorDescriptor descriptor,
Consumer<ReflectionHints> hints) {
Constructor<?> constructor = descriptor.constructor();
CodeWarnings codeWarnings = new CodeWarnings();
codeWarnings.detectDeprecation(constructor.getDeclaringClass(), constructor)
.detectDeprecation(Arrays.stream(constructor.getParameters()).map(Parameter::getType));
hints.accept(this.generationContext.getRuntimeHints().reflection());
GeneratedMethod generatedMethod = generateGetInstanceSupplierMethod(method -> {
method.addJavadoc("Get the bean instance supplier for '$L'.", beanName);
method.addJavadoc("Get the bean instance supplier for '$L'.", descriptor.beanName());
method.addModifiers(PRIVATE_STATIC);
codeWarnings.suppress(method);
method.returns(ParameterizedTypeName.get(BeanInstanceSupplier.class, constructor.getDeclaringClass()));
method.addStatement(generateResolverForConstructor(constructor));
method.returns(ParameterizedTypeName.get(BeanInstanceSupplier.class, descriptor.publicType()));
method.addStatement(generateResolverForConstructor(descriptor));
});
return generateReturnStatement(generatedMethod);
}
private void buildGetInstanceMethodForConstructor(MethodSpec.Builder method, String beanName,
Constructor<?> constructor, javax.lang.model.element.Modifier... modifiers) {
private void buildGetInstanceMethodForConstructor(MethodSpec.Builder method, ConstructorDescriptor descriptor,
javax.lang.model.element.Modifier... modifiers) {
Class<?> declaringClass = constructor.getDeclaringClass();
Constructor<?> constructor = descriptor.constructor();
Class<?> publicType = descriptor.publicType();
Class<?> actualType = descriptor.actualType();
CodeWarnings codeWarnings = new CodeWarnings();
codeWarnings.detectDeprecation(declaringClass, constructor)
codeWarnings.detectDeprecation(actualType, constructor)
.detectDeprecation(Arrays.stream(constructor.getParameters()).map(Parameter::getType));
method.addJavadoc("Get the bean instance supplier for '$L'.", beanName);
method.addJavadoc("Get the bean instance supplier for '$L'.", descriptor.beanName());
method.addModifiers(modifiers);
codeWarnings.suppress(method);
method.returns(ParameterizedTypeName.get(BeanInstanceSupplier.class, declaringClass));
method.returns(ParameterizedTypeName.get(BeanInstanceSupplier.class, publicType));
CodeBlock.Builder code = CodeBlock.builder();
code.add(generateResolverForConstructor(constructor));
code.add(generateResolverForConstructor(descriptor));
boolean hasArguments = constructor.getParameterCount() > 0;
boolean onInnerClass = ClassUtils.isInnerClass(declaringClass);
boolean onInnerClass = ClassUtils.isInnerClass(actualType);
CodeBlock arguments = hasArguments ?
new AutowiredArgumentsCodeGenerator(declaringClass, constructor)
new AutowiredArgumentsCodeGenerator(actualType, constructor)
.generateCode(constructor.getParameterTypes(), (onInnerClass ? 1 : 0))
: NO_ARGS;
CodeBlock newInstance = generateNewInstanceCodeForConstructor(declaringClass, arguments);
CodeBlock newInstance = generateNewInstanceCodeForConstructor(actualType, arguments);
code.add(generateWithGeneratorCode(hasArguments, newInstance));
method.addStatement(code.build());
}
private CodeBlock generateResolverForConstructor(Constructor<?> constructor) {
CodeBlock parameterTypes = generateParameterTypesCode(constructor.getParameterTypes());
private CodeBlock generateResolverForConstructor(ConstructorDescriptor descriptor) {
CodeBlock parameterTypes = generateParameterTypesCode(descriptor.constructor().getParameterTypes());
return CodeBlock.of("return $T.<$T>forConstructor($L)", BeanInstanceSupplier.class,
constructor.getDeclaringClass(), parameterTypes);
descriptor.publicType(), parameterTypes);
}
private CodeBlock generateNewInstanceCodeForConstructor(Class<?> declaringClass, CodeBlock args) {
@@ -438,4 +443,11 @@ public class InstanceSupplierCodeGenerator {
}
}
record ConstructorDescriptor(String beanName, Constructor<?> constructor, Class<?> publicType) {
Class<?> actualType() {
return this.constructor.getDeclaringClass();
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2024 the original author or authors.
* Copyright 2002-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -991,54 +991,64 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
*/
@Nullable
private FactoryBean<?> getSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) {
BeanWrapper bw = this.factoryBeanInstanceCache.get(beanName);
if (bw != null) {
return (FactoryBean<?>) bw.getWrappedInstance();
}
Object beanInstance = getSingleton(beanName, false);
if (beanInstance instanceof FactoryBean<?> factoryBean) {
return factoryBean;
}
if (isSingletonCurrentlyInCreation(beanName) ||
(mbd.getFactoryBeanName() != null && isSingletonCurrentlyInCreation(mbd.getFactoryBeanName()))) {
boolean locked = this.singletonLock.tryLock();
if (!locked) {
return null;
}
Object instance;
try {
// Mark this bean as currently in creation, even if just partially.
beforeSingletonCreation(beanName);
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
instance = resolveBeforeInstantiation(beanName, mbd);
if (instance == null) {
bw = createBeanInstance(beanName, mbd, null);
instance = bw.getWrappedInstance();
this.factoryBeanInstanceCache.put(beanName, bw);
BeanWrapper bw = this.factoryBeanInstanceCache.get(beanName);
if (bw != null) {
return (FactoryBean<?>) bw.getWrappedInstance();
}
}
catch (UnsatisfiedDependencyException ex) {
// Don't swallow, probably misconfiguration...
throw ex;
}
catch (BeanCreationException ex) {
// Don't swallow a linkage error since it contains a full stacktrace on
// first occurrence... and just a plain NoClassDefFoundError afterwards.
if (ex.contains(LinkageError.class)) {
Object beanInstance = getSingleton(beanName, false);
if (beanInstance instanceof FactoryBean<?> factoryBean) {
return factoryBean;
}
if (isSingletonCurrentlyInCreation(beanName) ||
(mbd.getFactoryBeanName() != null && isSingletonCurrentlyInCreation(mbd.getFactoryBeanName()))) {
return null;
}
Object instance;
try {
// Mark this bean as currently in creation, even if just partially.
beforeSingletonCreation(beanName);
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
instance = resolveBeforeInstantiation(beanName, mbd);
if (instance == null) {
bw = createBeanInstance(beanName, mbd, null);
instance = bw.getWrappedInstance();
this.factoryBeanInstanceCache.put(beanName, bw);
}
}
catch (UnsatisfiedDependencyException ex) {
// Don't swallow, probably misconfiguration...
throw ex;
}
// Instantiation failure, maybe too early...
if (logger.isDebugEnabled()) {
logger.debug("Bean creation exception on singleton FactoryBean type check: " + ex);
catch (BeanCreationException ex) {
// Don't swallow a linkage error since it contains a full stacktrace on
// first occurrence... and just a plain NoClassDefFoundError afterwards.
if (ex.contains(LinkageError.class)) {
throw ex;
}
// Instantiation failure, maybe too early...
if (logger.isDebugEnabled()) {
logger.debug("Bean creation exception on singleton FactoryBean type check: " + ex);
}
onSuppressedException(ex);
return null;
}
onSuppressedException(ex);
return null;
finally {
// Finished partial creation of this bean.
afterSingletonCreation(beanName);
}
return getFactoryBean(beanName, instance);
}
finally {
// Finished partial creation of this bean.
afterSingletonCreation(beanName);
this.singletonLock.unlock();
}
return getFactoryBean(beanName, instance);
}
/**
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -54,6 +54,22 @@ public class BeanDefinitionOverrideException extends BeanDefinitionStoreExceptio
this.existingDefinition = existingDefinition;
}
/**
* Create a new BeanDefinitionOverrideException for the given new and existing definition.
* @param beanName the name of the bean
* @param beanDefinition the newly registered bean definition
* @param existingDefinition the existing bean definition for the same name
* @param msg the detail message to include
* @since 6.2.1
*/
public BeanDefinitionOverrideException(
String beanName, BeanDefinition beanDefinition, BeanDefinition existingDefinition, String msg) {
super(beanDefinition.getResourceDescription(), beanName, msg);
this.beanDefinition = beanDefinition;
this.existingDefinition = existingDefinition;
}
/**
* Return the description of the resource that the bean definition came from.
@@ -177,7 +177,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
/** Map from bean name to merged BeanDefinitionHolder. */
private final Map<String, BeanDefinitionHolder> mergedBeanDefinitionHolders = new ConcurrentHashMap<>(256);
// Set of bean definition names with a primary marker. */
/** Set of bean definition names with a primary marker. */
private final Set<String> primaryBeanNames = ConcurrentHashMap.newKeySet(16);
/** Map of singleton and non-singleton bean names, keyed by dependency type. */
@@ -1170,6 +1170,11 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
}
}
else {
if (logger.isInfoEnabled()) {
logger.info("Removing alias '" + beanName + "' for bean '" + aliasedName +
"' due to registration of bean definition for bean '" + beanName + "': [" +
beanDefinition + "]");
}
removeAlias(beanName);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2024 the original author or authors.
* Copyright 2002-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -76,6 +76,9 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
private static final int SUPPRESSED_EXCEPTIONS_LIMIT = 100;
/** Common lock for singleton creation. */
final Lock singletonLock = new ReentrantLock();
/** Cache of singleton objects: bean name to bean instance. */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
@@ -91,8 +94,6 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
/** Set of registered singletons, containing the bean names in registration order. */
private final Set<String> registeredSingletons = Collections.synchronizedSet(new LinkedHashSet<>(256));
private final Lock singletonLock = new ReentrantLock();
/** Names of beans that are currently in creation. */
private final Set<String> singletonsCurrentlyInCreation = ConcurrentHashMap.newKeySet(16);
@@ -278,7 +279,25 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
beforeSingletonCreation(beanName);
try {
beforeSingletonCreation(beanName);
}
catch (BeanCurrentlyInCreationException ex) {
if (locked) {
throw ex;
}
// Try late locking for waiting on specific bean to be finished.
this.singletonLock.lock();
locked = true;
// Singleton object should have appeared in the meantime.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject != null) {
return singletonObject;
}
beforeSingletonCreation(beanName);
}
boolean newSingleton = false;
boolean recordSuppressedExceptions = (locked && this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
@@ -118,39 +118,45 @@ public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanReg
*/
protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
if (factory.isSingleton() && containsSingleton(beanName)) {
Object object = this.factoryBeanObjectCache.get(beanName);
if (object == null) {
object = doGetObjectFromFactoryBean(factory, beanName);
// Only post-process and store if not put there already during getObject() call above
// (for example, because of circular reference processing triggered by custom getBean calls)
Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
if (alreadyThere != null) {
object = alreadyThere;
}
else {
if (shouldPostProcess) {
if (isSingletonCurrentlyInCreation(beanName)) {
// Temporarily return non-post-processed object, not storing it yet
return object;
this.singletonLock.lock();
try {
Object object = this.factoryBeanObjectCache.get(beanName);
if (object == null) {
object = doGetObjectFromFactoryBean(factory, beanName);
// Only post-process and store if not put there already during getObject() call above
// (for example, because of circular reference processing triggered by custom getBean calls)
Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
if (alreadyThere != null) {
object = alreadyThere;
}
else {
if (shouldPostProcess) {
if (isSingletonCurrentlyInCreation(beanName)) {
// Temporarily return non-post-processed object, not storing it yet
return object;
}
beforeSingletonCreation(beanName);
try {
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName,
"Post-processing of FactoryBean's singleton object failed", ex);
}
finally {
afterSingletonCreation(beanName);
}
}
beforeSingletonCreation(beanName);
try {
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName,
"Post-processing of FactoryBean's singleton object failed", ex);
}
finally {
afterSingletonCreation(beanName);
if (containsSingleton(beanName)) {
this.factoryBeanObjectCache.put(beanName, object);
}
}
if (containsSingleton(beanName)) {
this.factoryBeanObjectCache.put(beanName, object);
}
}
return object;
}
finally {
this.singletonLock.unlock();
}
return object;
}
else {
Object object = doGetObjectFromFactoryBean(factory, beanName);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2024 the original author or authors.
* Copyright 2002-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,7 +23,6 @@ import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.testfixture.beans.TestBean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Juergen Hoeller
@@ -56,9 +55,6 @@ class BeanFactoryLockingTests {
@Override
public void afterPropertiesSet() throws Exception {
Thread thread = new Thread(() -> {
// Fail for circular reference from other thread
assertThatExceptionOfType(BeanCurrentlyInCreationException.class).isThrownBy(() ->
beanFactory.getBean(ThreadDuringInitialization.class));
// Leniently create unrelated other bean outside of singleton lock
assertThat(beanFactory.getBean(TestBean.class).getName()).isEqualTo("tb");
// Creation attempt in other thread was successful
@@ -870,10 +870,15 @@ class DefaultListableBeanFactoryTests {
void beanDefinitionOverriding() {
lbf.setAllowBeanDefinitionOverriding(true);
lbf.registerBeanDefinition("test", new RootBeanDefinition(TestBean.class));
// Override "test" bean definition.
lbf.registerBeanDefinition("test", new RootBeanDefinition(NestedTestBean.class));
// Temporary "test2" alias for nonexistent bean.
lbf.registerAlias("otherTest", "test2");
// Reassign "test2" alias to "test".
lbf.registerAlias("test", "test2");
// Assign "testX" alias to "test" as well.
lbf.registerAlias("test", "testX");
// Register new "testX" bean definition which also removes the "testX" alias for "test".
lbf.registerBeanDefinition("testX", new RootBeanDefinition(TestBean.class));
assertThat(lbf.getBean("test")).isInstanceOf(NestedTestBean.class);
@@ -36,10 +36,10 @@ import org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader;
import org.springframework.beans.factory.parsing.SourceExtractor;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinitionReader;
import org.springframework.beans.factory.support.BeanDefinitionOverrideException;
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.ConfigurationCondition.ConfigurationPhase;
@@ -297,13 +297,21 @@ class ConfigurationClassBeanDefinitionReader {
return false;
}
BeanDefinition existingBeanDef = this.registry.getBeanDefinition(beanName);
ConfigurationClass configClass = beanMethod.getConfigurationClass();
// If the bean method is an overloaded case on the same configuration class,
// preserve the existing bean definition and mark it as overloaded.
if (existingBeanDef instanceof ConfigurationClassBeanDefinition ccbd) {
if (ccbd.getMetadata().getClassName().equals(beanMethod.getConfigurationClass().getMetadata().getClassName()) &&
ccbd.getFactoryMethodMetadata().getMethodName().equals(beanMethod.getMetadata().getMethodName())) {
ccbd.setNonUniqueFactoryMethodName(ccbd.getFactoryMethodMetadata().getMethodName());
if (ccbd.getMetadata().getClassName().equals(configClass.getMetadata().getClassName())) {
if (ccbd.getFactoryMethodMetadata().getMethodName().equals(beanMethod.getMetadata().getMethodName())) {
ccbd.setNonUniqueFactoryMethodName(ccbd.getFactoryMethodMetadata().getMethodName());
}
else if (!this.registry.isBeanDefinitionOverridable(beanName)) {
throw new BeanDefinitionOverrideException(beanName,
new ConfigurationClassBeanDefinition(configClass, beanMethod.getMetadata(), beanName),
existingBeanDef,
"@Bean method override with same bean name but different method name: " + existingBeanDef);
}
return true;
}
else {
@@ -329,9 +337,11 @@ class ConfigurationClassBeanDefinitionReader {
// At this point, it's a top-level override (probably XML), just having been parsed
// before configuration class processing kicks in...
if (this.registry instanceof DefaultListableBeanFactory dlbf && !dlbf.isBeanDefinitionOverridable(beanName)) {
throw new BeanDefinitionStoreException(beanMethod.getConfigurationClass().getResource().getDescription(),
beanName, "@Bean definition illegally overridden by existing bean definition: " + existingBeanDef);
if (!this.registry.isBeanDefinitionOverridable(beanName)) {
throw new BeanDefinitionOverrideException(beanName,
new ConfigurationClassBeanDefinition(configClass, beanMethod.getMetadata(), beanName),
existingBeanDef,
"@Bean definition illegally overridden by existing bean definition: " + existingBeanDef);
}
if (logger.isDebugEnabled()) {
logger.debug(String.format("Skipping bean definition for %s: a definition for bean '%s' " +
@@ -29,7 +29,8 @@ import org.springframework.lang.Nullable;
/**
* Declares that a field or method parameter should be formatted as a
* {@link java.time.Duration}, according to the specified {@link #style style}.
* {@link java.time.Duration}, according to the specified {@link #style Style}
* and {@link #defaultUnit Unit}.
*
* @author Simon Baslé
* @since 6.2
@@ -40,20 +41,20 @@ import org.springframework.lang.Nullable;
public @interface DurationFormat {
/**
* The {@code Style} to use for parsing and printing a {@code Duration}.
* The {@link Style} to use for parsing and printing a {@link Duration}.
* <p>Defaults to the JDK style ({@link Style#ISO8601}).
*/
Style style() default Style.ISO8601;
/**
* The {@link Unit} to fall back to in case the {@code style()} needs a unit
* The {@link Unit} to fall back to in case the {@link #style Style} needs a unit
* for either parsing or printing, and none is explicitly provided in the input.
* <p>Defaults to {@link Unit#MILLIS} if unspecified.
*/
Unit defaultUnit() default Unit.MILLIS;
/**
* Duration format styles.
* {@link Duration} format styles.
*/
enum Style {
@@ -62,7 +63,7 @@ public @interface DurationFormat {
* <p>Supported unit suffixes include: {@code ns, us, ms, s, m, h, d}.
* Those correspond to nanoseconds, microseconds, milliseconds, seconds,
* minutes, hours, and days, respectively.
* <p>Note that when printing a {@code Duration}, this style can be
* <p>Note that when printing a {@link Duration}, this style can be
* lossy if the selected unit is bigger than the resolution of the
* duration. For example, {@code Duration.ofMillis(5).plusNanos(1234)}
* would get truncated to {@code "5ms"} when printing using
@@ -73,7 +74,7 @@ public @interface DurationFormat {
/**
* ISO-8601 formatting.
* <p>This is what the JDK uses in {@link java.time.Duration#parse(CharSequence)}
* <p>This is what the JDK uses in {@link Duration#parse(CharSequence)}
* and {@link Duration#toString()}.
*/
ISO8601,
@@ -90,11 +91,11 @@ public @interface DurationFormat {
}
/**
* Duration format unit, which mirrors a subset of {@link ChronoUnit} and
* {@link Duration} format unit, which mirrors a subset of {@link ChronoUnit} and
* allows conversion to and from a supported {@code ChronoUnit} as well as
* conversion from durations to longs.
*
* <p>The enum includes its corresponding suffix in the {@link Style#SIMPLE simple}
* <p>The enum includes its corresponding suffix in the {@link Style#SIMPLE SIMPLE}
* {@code Duration} format style.
*/
enum Unit {
@@ -147,25 +148,24 @@ public @interface DurationFormat {
}
/**
* Convert this {@code DurationFormat.Unit} to its {@link ChronoUnit}
* equivalent.
* Convert this {@code Unit} to its {@link ChronoUnit} equivalent.
*/
public ChronoUnit asChronoUnit() {
return this.chronoUnit;
}
/**
* Convert this {@code DurationFormat.Unit} to a simple {@code String}
* suffix, suitable for the {@link Style#SIMPLE SIMPLE} style.
* Convert this {@code Unit} to a simple {@code String} suffix, suitable
* for the {@link Style#SIMPLE SIMPLE} style.
*/
public String asSuffix() {
return this.suffix;
}
/**
* Parse a {@code long} from a {@code String} and interpret it to be a
* {@code Duration} in the current unit.
* @param value the String representation of the long
* Parse a {@code long} from the given {@link String} and interpret it to be a
* {@link Duration} in the current unit.
* @param value the {@code String} representation of the long
* @return the corresponding {@code Duration}
*/
public Duration parse(String value) {
@@ -173,11 +173,11 @@ public @interface DurationFormat {
}
/**
* Print a {@code Duration} as a {@code String}, converting it to a long
* Print the given {@link Duration} as a {@link String}, converting it to a long
* value using this unit's precision via {@link #longValue(Duration)}
* and appending this unit's simple {@link #asSuffix() suffix}.
* @param value the {@code Duration} to convert to a String
* @return the String representation of the {@code Duration} in the
* @param value the {@code Duration} to convert to a {@code String}
* @return the {@code String} representation of the {@code Duration} in the
* {@link Style#SIMPLE SIMPLE} style
*/
public String print(Duration value) {
@@ -185,11 +185,12 @@ public @interface DurationFormat {
}
/**
* Convert the given {@code Duration} to a long value in the resolution
* of this unit. Note that this can be lossy if the current unit is
* bigger than the actual resolution of the duration.
* <p>For example, {@code Duration.ofMillis(5).plusNanos(1234)} would
* get truncated to {@code 5} for unit {@code MILLIS}.
* Convert the given {@link Duration} to a long value in the resolution
* of this unit.
* <p>Note that this can be lossy if the current unit is bigger than the
* actual resolution of the duration. For example,
* {@code Duration.ofMillis(5).plusNanos(1234)} would get truncated to
* {@code 5} for unit {@code MILLIS}.
* @param value the {@code Duration} to convert to a long
* @return the long value for the {@code Duration} in this {@code Unit}
*/
@@ -198,7 +199,7 @@ public @interface DurationFormat {
}
/**
* Get the {@code Unit} corresponding to the given {@code ChronoUnit}.
* Get the {@link Unit} corresponding to the given {@link ChronoUnit}.
* @throws IllegalArgumentException if the given {@code ChronoUnit} is
* not supported
*/
@@ -215,7 +216,7 @@ public @interface DurationFormat {
}
/**
* Get the {@code Unit} corresponding to the given {@code String} suffix.
* Get the {@link Unit} corresponding to the given {@link String} suffix.
* @throws IllegalArgumentException if the given suffix is not supported
*/
public static Unit fromSuffix(String suffix) {
@@ -123,8 +123,9 @@ abstract class ScheduledAnnotationReactiveSupport {
Publisher<?> publisher = getPublisherFor(method, targetBean);
Supplier<ScheduledTaskObservationContext> contextSupplier =
() -> new ScheduledTaskObservationContext(targetBean, method);
String displayName = targetBean.getClass().getName() + "." + method.getName();
return new SubscribingRunnable(publisher, shouldBlock, scheduled.scheduler(),
subscriptionTrackerRegistry, observationRegistrySupplier, contextSupplier);
subscriptionTrackerRegistry, displayName, observationRegistrySupplier, contextSupplier);
}
/**
@@ -192,6 +193,8 @@ abstract class ScheduledAnnotationReactiveSupport {
final boolean shouldBlock;
final String displayName;
@Nullable
private final String qualifier;
@@ -202,12 +205,13 @@ abstract class ScheduledAnnotationReactiveSupport {
final Supplier<ScheduledTaskObservationContext> contextSupplier;
SubscribingRunnable(Publisher<?> publisher, boolean shouldBlock,
@Nullable String qualifier, List<Runnable> subscriptionTrackerRegistry,
Supplier<ObservationRegistry> observationRegistrySupplier,
Supplier<ScheduledTaskObservationContext> contextSupplier) {
@Nullable String qualifier, List<Runnable> subscriptionTrackerRegistry,
String displayName, Supplier<ObservationRegistry> observationRegistrySupplier,
Supplier<ScheduledTaskObservationContext> contextSupplier) {
this.publisher = publisher;
this.shouldBlock = shouldBlock;
this.displayName = displayName;
this.qualifier = qualifier;
this.subscriptionTrackerRegistry = subscriptionTrackerRegistry;
this.observationRegistrySupplier = observationRegistrySupplier;
@@ -253,6 +257,11 @@ abstract class ScheduledAnnotationReactiveSupport {
this.publisher.subscribe(subscriber);
}
}
@Override
public String toString() {
return this.displayName;
}
}
@@ -18,6 +18,8 @@ package org.springframework.scheduling.config;
import java.time.Instant;
import org.springframework.lang.Nullable;
import org.springframework.scheduling.SchedulingAwareRunnable;
import org.springframework.util.Assert;
/**
@@ -68,7 +70,7 @@ public class Task {
}
private class OutcomeTrackingRunnable implements Runnable {
private class OutcomeTrackingRunnable implements SchedulingAwareRunnable {
private final Runnable runnable;
@@ -89,6 +91,23 @@ public class Task {
}
}
@Override
public boolean isLongLived() {
if (this.runnable instanceof SchedulingAwareRunnable sar) {
return sar.isLongLived();
}
return SchedulingAwareRunnable.super.isLongLived();
}
@Nullable
@Override
public String getQualifier() {
if (this.runnable instanceof SchedulingAwareRunnable sar) {
return sar.getQualifier();
}
return SchedulingAwareRunnable.super.getQualifier();
}
@Override
public String toString() {
return this.runnable.toString();
@@ -1060,7 +1060,9 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter {
}
int size = (indexes.last() < this.autoGrowCollectionLimit ? indexes.last() + 1 : 0);
List<V> list = (List<V>) CollectionFactory.createCollection(paramType, size);
indexes.forEach(i -> list.add(null));
for (int i = 0; i < size; i++) {
list.add(null);
}
for (int index : indexes) {
list.set(index, (V) createObject(elementType, paramPath + "[" + index + "].", valueResolver));
}
@@ -1080,7 +1082,7 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter {
}
int startIdx = paramPath.length() + 1;
int endIdx = name.indexOf(']', startIdx);
String nestedPath = name.substring(0, endIdx + 2);
String nestedPath = ((name.length() > endIdx + 1) ? name.substring(0, endIdx + 2) : "");
boolean quoted = (endIdx - startIdx > 2 && name.charAt(startIdx) == '\'' && name.charAt(endIdx - 1) == '\'');
String key = (quoted ? name.substring(startIdx + 1, endIdx - 1) : name.substring(startIdx, endIdx));
if (map == null) {
@@ -1114,7 +1116,7 @@ public class DataBinder implements PropertyEditorRegistry, TypeConverter {
SortedSet<Integer> indexes = null;
for (String name : valueResolver.getNames()) {
if (name.startsWith(paramPath + "[")) {
int endIndex = name.indexOf(']', paramPath.length() + 2);
int endIndex = name.indexOf(']', paramPath.length() + 1);
String rawIndex = name.substring(paramPath.length() + 1, endIndex);
int index = Integer.parseInt(rawIndex);
indexes = (indexes != null ? indexes : new TreeSet<>());
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,7 +18,6 @@ package org.springframework.validation.beanvalidation;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
@@ -107,7 +106,7 @@ class BeanValidationBeanRegistrationAotProcessor implements BeanRegistrationAotP
Set<Class<?>> validatedClasses = new HashSet<>();
Set<Class<? extends ConstraintValidator<?, ?>>> constraintValidatorClasses = new HashSet<>();
processAheadOfTime(beanClass, validatedClasses, constraintValidatorClasses);
processAheadOfTime(beanClass, new HashSet<>(), validatedClasses, constraintValidatorClasses);
if (!validatedClasses.isEmpty() || !constraintValidatorClasses.isEmpty()) {
return new AotContribution(validatedClasses, constraintValidatorClasses);
@@ -115,27 +114,38 @@ class BeanValidationBeanRegistrationAotProcessor implements BeanRegistrationAotP
return null;
}
private static void processAheadOfTime(Class<?> clazz, Collection<Class<?>> validatedClasses,
Collection<Class<? extends ConstraintValidator<?, ?>>> constraintValidatorClasses) {
private static void processAheadOfTime(Class<?> clazz, Set<Class<?>> visitedClasses, Set<Class<?>> validatedClasses,
Set<Class<? extends ConstraintValidator<?, ?>>> constraintValidatorClasses) {
Assert.notNull(validator, "Validator can't be null");
Assert.notNull(validator, "Validator cannot be null");
if (!visitedClasses.add(clazz)) {
return;
}
BeanDescriptor descriptor;
try {
descriptor = validator.getConstraintsForClass(clazz);
}
catch (RuntimeException ex) {
catch (RuntimeException | LinkageError ex) {
String className = clazz.getName();
if (KotlinDetector.isKotlinType(clazz) && ex instanceof ArrayIndexOutOfBoundsException) {
// See https://hibernate.atlassian.net/browse/HV-1796 and https://youtrack.jetbrains.com/issue/KT-40857
logger.warn("Skipping validation constraint hint inference for class " + clazz +
" due to an ArrayIndexOutOfBoundsException at validator level");
if (logger.isWarnEnabled()) {
logger.warn("Skipping validation constraint hint inference for class " + className +
" due to an ArrayIndexOutOfBoundsException at validator level");
}
}
else if (ex instanceof TypeNotPresentException) {
logger.debug("Skipping validation constraint hint inference for class " +
clazz + " due to a TypeNotPresentException at validator level: " + ex.getMessage());
else if (ex instanceof TypeNotPresentException || ex instanceof NoClassDefFoundError) {
if (logger.isDebugEnabled()) {
logger.debug("Skipping validation constraint hint inference for class %s due to a %s for %s"
.formatted(className, ex.getClass().getSimpleName(), ex.getMessage()));
}
}
else {
logger.warn("Skipping validation constraint hint inference for class " + clazz, ex);
if (logger.isWarnEnabled()) {
logger.warn("Skipping validation constraint hint inference for class " + className, ex);
}
}
return;
}
@@ -149,12 +159,12 @@ class BeanValidationBeanRegistrationAotProcessor implements BeanRegistrationAotP
ReflectionUtils.doWithFields(clazz, field -> {
Class<?> type = field.getType();
if (Iterable.class.isAssignableFrom(type) || List.class.isAssignableFrom(type) || Optional.class.isAssignableFrom(type)) {
if (Iterable.class.isAssignableFrom(type) || Optional.class.isAssignableFrom(type)) {
ResolvableType resolvableType = ResolvableType.forField(field);
Class<?> genericType = resolvableType.getGeneric(0).toClass();
if (shouldProcess(genericType)) {
validatedClasses.add(clazz);
processAheadOfTime(genericType, validatedClasses, constraintValidatorClasses);
processAheadOfTime(genericType, visitedClasses, validatedClasses, constraintValidatorClasses);
}
}
if (Map.class.isAssignableFrom(type)) {
@@ -163,11 +173,11 @@ class BeanValidationBeanRegistrationAotProcessor implements BeanRegistrationAotP
Class<?> valueGenericType = resolvableType.getGeneric(1).toClass();
if (shouldProcess(keyGenericType)) {
validatedClasses.add(clazz);
processAheadOfTime(keyGenericType, validatedClasses, constraintValidatorClasses);
processAheadOfTime(keyGenericType, visitedClasses, validatedClasses, constraintValidatorClasses);
}
if (shouldProcess(valueGenericType)) {
validatedClasses.add(clazz);
processAheadOfTime(valueGenericType, validatedClasses, constraintValidatorClasses);
processAheadOfTime(valueGenericType, visitedClasses, validatedClasses, constraintValidatorClasses);
}
}
});
@@ -367,7 +367,7 @@ public class MethodValidationAdapter implements MethodValidator {
container = null;
}
if (node.getKind().equals(ElementKind.PROPERTY)) {
if (node.getKind().equals(ElementKind.PROPERTY) || node.getKind().equals(ElementKind.BEAN)) {
nestedViolations
.computeIfAbsent(parameterNode, k ->
new ParamErrorsBuilder(parameter, value, container, index, key))
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2013 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
package org.springframework.validation.beanvalidation;
import jakarta.validation.ValidationException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
@@ -39,7 +40,13 @@ public class OptionalValidatorFactoryBean extends LocalValidatorFactoryBean {
super.afterPropertiesSet();
}
catch (ValidationException ex) {
LogFactory.getLog(getClass()).debug("Failed to set up a Bean Validation provider", ex);
Log logger = LogFactory.getLog(getClass());
if (logger.isDebugEnabled()) {
logger.debug("Failed to set up a Bean Validation provider", ex);
}
else if (logger.isInfoEnabled()) {
logger.info("Failed to set up a Bean Validation provider: " + ex);
}
}
}
@@ -85,7 +85,7 @@ class AspectJAutoProxyCreatorTests {
void aspectsAreApplied() {
ClassPathXmlApplicationContext bf = newContext("aspects.xml");
ITestBean tb = (ITestBean) bf.getBean("adrian");
ITestBean tb = bf.getBean("adrian", ITestBean.class);
assertThat(tb.getAge()).isEqualTo(68);
MethodInvokingFactoryBean factoryBean = (MethodInvokingFactoryBean) bf.getBean("&factoryBean");
assertThat(AopUtils.isAopProxy(factoryBean.getTargetObject())).isTrue();
@@ -96,7 +96,7 @@ class AspectJAutoProxyCreatorTests {
void multipleAspectsWithParameterApplied() {
ClassPathXmlApplicationContext bf = newContext("aspects.xml");
ITestBean tb = (ITestBean) bf.getBean("adrian");
ITestBean tb = bf.getBean("adrian", ITestBean.class);
tb.setAge(10);
assertThat(tb.getAge()).isEqualTo(20);
}
@@ -105,7 +105,7 @@ class AspectJAutoProxyCreatorTests {
void aspectsAreAppliedInDefinedOrder() {
ClassPathXmlApplicationContext bf = newContext("aspectsWithOrdering.xml");
ITestBean tb = (ITestBean) bf.getBean("adrian");
ITestBean tb = bf.getBean("adrian", ITestBean.class);
assertThat(tb.getAge()).isEqualTo(71);
}
@@ -113,8 +113,8 @@ class AspectJAutoProxyCreatorTests {
void aspectsAndAdvisorAreApplied() {
ClassPathXmlApplicationContext ac = newContext("aspectsPlusAdvisor.xml");
ITestBean shouldBeWeaved = (ITestBean) ac.getBean("adrian");
doTestAspectsAndAdvisorAreApplied(ac, shouldBeWeaved);
ITestBean shouldBeWoven = ac.getBean("adrian", ITestBean.class);
assertAspectsAndAdvisorAreApplied(ac, shouldBeWoven);
}
@Test
@@ -124,20 +124,22 @@ class AspectJAutoProxyCreatorTests {
GenericApplicationContext childAc = new GenericApplicationContext(ac);
// Create a child factory with a bean that should be woven
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.getPropertyValues().addPropertyValue(new PropertyValue("name", "Adrian"))
bd.getPropertyValues()
.addPropertyValue(new PropertyValue("name", "Adrian"))
.addPropertyValue(new PropertyValue("age", 34));
childAc.registerBeanDefinition("adrian2", bd);
// Register the advisor auto proxy creator with subclass
childAc.registerBeanDefinition(AnnotationAwareAspectJAutoProxyCreator.class.getName(), new RootBeanDefinition(
AnnotationAwareAspectJAutoProxyCreator.class));
childAc.registerBeanDefinition(AnnotationAwareAspectJAutoProxyCreator.class.getName(),
new RootBeanDefinition(AnnotationAwareAspectJAutoProxyCreator.class));
childAc.refresh();
ITestBean beanFromChildContextThatShouldBeWeaved = (ITestBean) childAc.getBean("adrian2");
//testAspectsAndAdvisorAreApplied(childAc, (ITestBean) ac.getBean("adrian"));
doTestAspectsAndAdvisorAreApplied(childAc, beanFromChildContextThatShouldBeWeaved);
ITestBean beanFromParentContextThatShouldBeWoven = ac.getBean("adrian", ITestBean.class);
ITestBean beanFromChildContextThatShouldBeWoven = childAc.getBean("adrian2", ITestBean.class);
assertAspectsAndAdvisorAreApplied(childAc, beanFromParentContextThatShouldBeWoven);
assertAspectsAndAdvisorAreApplied(childAc, beanFromChildContextThatShouldBeWoven);
}
protected void doTestAspectsAndAdvisorAreApplied(ApplicationContext ac, ITestBean shouldBeWeaved) {
protected void assertAspectsAndAdvisorAreApplied(ApplicationContext ac, ITestBean shouldBeWoven) {
TestBeanAdvisor tba = (TestBeanAdvisor) ac.getBean("advisor");
MultiplyReturnValue mrv = (MultiplyReturnValue) ac.getBean("aspect");
@@ -146,10 +148,10 @@ class AspectJAutoProxyCreatorTests {
tba.count = 0;
mrv.invocations = 0;
assertThat(AopUtils.isAopProxy(shouldBeWeaved)).as("Autoproxying must apply from @AspectJ aspect").isTrue();
assertThat(shouldBeWeaved.getName()).isEqualTo("Adrian");
assertThat(AopUtils.isAopProxy(shouldBeWoven)).as("Autoproxying must apply from @AspectJ aspect").isTrue();
assertThat(shouldBeWoven.getName()).isEqualTo("Adrian");
assertThat(mrv.invocations).isEqualTo(0);
assertThat(shouldBeWeaved.getAge()).isEqualTo((34 * mrv.getMultiple()));
assertThat(shouldBeWoven.getAge()).isEqualTo((34 * mrv.getMultiple()));
assertThat(tba.count).as("Spring advisor must be invoked").isEqualTo(2);
assertThat(mrv.invocations).as("Must be able to hold state in aspect").isEqualTo(1);
}
@@ -158,13 +160,13 @@ class AspectJAutoProxyCreatorTests {
void perThisAspect() {
ClassPathXmlApplicationContext bf = newContext("perthis.xml");
ITestBean adrian1 = (ITestBean) bf.getBean("adrian");
ITestBean adrian1 = bf.getBean("adrian", ITestBean.class);
assertThat(AopUtils.isAopProxy(adrian1)).isTrue();
assertThat(adrian1.getAge()).isEqualTo(0);
assertThat(adrian1.getAge()).isEqualTo(1);
ITestBean adrian2 = (ITestBean) bf.getBean("adrian");
ITestBean adrian2 = bf.getBean("adrian", ITestBean.class);
assertThat(adrian2).isNotSameAs(adrian1);
assertThat(AopUtils.isAopProxy(adrian1)).isTrue();
assertThat(adrian2.getAge()).isEqualTo(0);
@@ -178,7 +180,7 @@ class AspectJAutoProxyCreatorTests {
void perTargetAspect() throws SecurityException, NoSuchMethodException {
ClassPathXmlApplicationContext bf = newContext("pertarget.xml");
ITestBean adrian1 = (ITestBean) bf.getBean("adrian");
ITestBean adrian1 = bf.getBean("adrian", ITestBean.class);
assertThat(AopUtils.isAopProxy(adrian1)).isTrue();
// Does not trigger advice or count
@@ -199,7 +201,7 @@ class AspectJAutoProxyCreatorTests {
adrian1.setName("Adrian");
//assertEquals("Any other setter does not increment", 2, adrian1.getAge());
ITestBean adrian2 = (ITestBean) bf.getBean("adrian");
ITestBean adrian2 = bf.getBean("adrian", ITestBean.class);
assertThat(adrian2).isNotSameAs(adrian1);
assertThat(AopUtils.isAopProxy(adrian1)).isTrue();
assertThat(adrian2.getAge()).isEqualTo(34);
@@ -239,7 +241,7 @@ class AspectJAutoProxyCreatorTests {
void twoAdviceAspect() {
ClassPathXmlApplicationContext bf = newContext("twoAdviceAspect.xml");
ITestBean adrian1 = (ITestBean) bf.getBean("adrian");
ITestBean adrian1 = bf.getBean("adrian", ITestBean.class);
testAgeAspect(adrian1, 0, 2);
}
@@ -247,9 +249,9 @@ class AspectJAutoProxyCreatorTests {
void twoAdviceAspectSingleton() {
ClassPathXmlApplicationContext bf = newContext("twoAdviceAspectSingleton.xml");
ITestBean adrian1 = (ITestBean) bf.getBean("adrian");
ITestBean adrian1 = bf.getBean("adrian", ITestBean.class);
testAgeAspect(adrian1, 0, 1);
ITestBean adrian2 = (ITestBean) bf.getBean("adrian");
ITestBean adrian2 = bf.getBean("adrian", ITestBean.class);
assertThat(adrian2).isNotSameAs(adrian1);
testAgeAspect(adrian2, 2, 1);
}
@@ -258,9 +260,9 @@ class AspectJAutoProxyCreatorTests {
void twoAdviceAspectPrototype() {
ClassPathXmlApplicationContext bf = newContext("twoAdviceAspectPrototype.xml");
ITestBean adrian1 = (ITestBean) bf.getBean("adrian");
ITestBean adrian1 = bf.getBean("adrian", ITestBean.class);
testAgeAspect(adrian1, 0, 1);
ITestBean adrian2 = (ITestBean) bf.getBean("adrian");
ITestBean adrian2 = bf.getBean("adrian", ITestBean.class);
assertThat(adrian2).isNotSameAs(adrian1);
testAgeAspect(adrian2, 0, 1);
}
@@ -280,7 +282,7 @@ class AspectJAutoProxyCreatorTests {
void adviceUsingJoinPoint() {
ClassPathXmlApplicationContext bf = newContext("usesJoinPointAspect.xml");
ITestBean adrian1 = (ITestBean) bf.getBean("adrian");
ITestBean adrian1 = bf.getBean("adrian", ITestBean.class);
adrian1.getAge();
AdviceUsingThisJoinPoint aspectInstance = (AdviceUsingThisJoinPoint) bf.getBean("aspect");
//(AdviceUsingThisJoinPoint) Aspects.aspectOf(AdviceUsingThisJoinPoint.class);
@@ -292,7 +294,7 @@ class AspectJAutoProxyCreatorTests {
void includeMechanism() {
ClassPathXmlApplicationContext bf = newContext("usesInclude.xml");
ITestBean adrian = (ITestBean) bf.getBean("adrian");
ITestBean adrian = bf.getBean("adrian", ITestBean.class);
assertThat(AopUtils.isAopProxy(adrian)).isTrue();
assertThat(adrian.getAge()).isEqualTo(68);
}
@@ -310,7 +312,7 @@ class AspectJAutoProxyCreatorTests {
void withAbstractFactoryBeanAreApplied() {
ClassPathXmlApplicationContext bf = newContext("aspectsWithAbstractBean.xml");
ITestBean adrian = (ITestBean) bf.getBean("adrian");
ITestBean adrian = bf.getBean("adrian", ITestBean.class);
assertThat(AopUtils.isAopProxy(adrian)).isTrue();
assertThat(adrian.getAge()).isEqualTo(68);
}
@@ -321,8 +323,7 @@ class AspectJAutoProxyCreatorTests {
UnreliableBean bean = (UnreliableBean) bf.getBean("unreliableBean");
RetryAspect aspect = (RetryAspect) bf.getBean("retryAspect");
int attempts = bean.unreliable();
assertThat(attempts).isEqualTo(2);
assertThat(bean.unreliable()).isEqualTo(2);
assertThat(aspect.getBeginCalls()).isEqualTo(2);
assertThat(aspect.getRollbackCalls()).isEqualTo(1);
assertThat(aspect.getCommitCalls()).isEqualTo(1);
@@ -332,7 +333,7 @@ class AspectJAutoProxyCreatorTests {
void withBeanNameAutoProxyCreator() {
ClassPathXmlApplicationContext bf = newContext("withBeanNameAutoProxyCreator.xml");
ITestBean tb = (ITestBean) bf.getBean("adrian");
ITestBean tb = bf.getBean("adrian", ITestBean.class);
assertThat(tb.getAge()).isEqualTo(68);
}
@@ -0,0 +1,98 @@
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.framework.autoproxy;
import java.lang.reflect.Method;
import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.junit.jupiter.api.Test;
import org.springframework.aop.Pointcut;
import org.springframework.aop.support.AbstractPointcutAdvisor;
import org.springframework.aop.support.RootClassFilter;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for {@link DefaultAdvisorAutoProxyCreator}.
*
* @author Sam Brannen
* @since 6.2.1
*/
class DefaultAdvisorAutoProxyCreatorTests {
/**
* Indirectly tests behavior of {@link org.springframework.aop.framework.AdvisedSupport.MethodCacheKey}.
* @see StaticMethodMatcherPointcut#matches(Method, Class)
*/
@Test // gh-33915
void staticMethodMatcherPointcutMatchesMethodIsNotInvokedAgainForActualMethodInvocation() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
DemoBean.class, DemoPointcutAdvisor.class, DefaultAdvisorAutoProxyCreator.class);
DemoPointcutAdvisor demoPointcutAdvisor = context.getBean(DemoPointcutAdvisor.class);
DemoBean demoBean = context.getBean(DemoBean.class);
assertThat(demoPointcutAdvisor.matchesInvocationCount).as("matches() invocations before").isEqualTo(2);
// Invoke multiple times to ensure additional invocations don't affect the outcome.
assertThat(demoBean.sayHello()).isEqualTo("Advised: Hello!");
assertThat(demoBean.sayHello()).isEqualTo("Advised: Hello!");
assertThat(demoBean.sayHello()).isEqualTo("Advised: Hello!");
assertThat(demoPointcutAdvisor.matchesInvocationCount).as("matches() invocations after").isEqualTo(2);
context.close();
}
static class DemoBean {
public String sayHello() {
return "Hello!";
}
}
@SuppressWarnings("serial")
static class DemoPointcutAdvisor extends AbstractPointcutAdvisor {
int matchesInvocationCount = 0;
@Override
public Pointcut getPointcut() {
StaticMethodMatcherPointcut pointcut = new StaticMethodMatcherPointcut() {
@Override
public boolean matches(Method method, Class<?> targetClass) {
if (method.getName().equals("sayHello")) {
matchesInvocationCount++;
return true;
}
return false;
}
};
pointcut.setClassFilter(new RootClassFilter(DemoBean.class));
return pointcut;
}
@Override
public Advice getAdvice() {
return (MethodInterceptor) invocation -> "Advised: " + invocation.proceed();
}
}
}
@@ -110,7 +110,7 @@ class ConfigurationClassProcessingTests {
private void aliasesAreRespected(Class<?> testClass, Supplier<TestBean> testBeanSupplier, String beanName) {
TestBean testBean = testBeanSupplier.get();
BeanFactory factory = initBeanFactory(testClass);
BeanFactory factory = initBeanFactory(false, testClass);
assertThat(factory.getBean(beanName)).isSameAs(testBean);
Arrays.stream(factory.getAliases(beanName)).map(factory::getBean).forEach(alias -> assertThat(alias).isSameAs(testBean));
@@ -141,30 +141,30 @@ class ConfigurationClassProcessingTests {
@Test
void finalBeanMethod() {
assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(() ->
initBeanFactory(ConfigWithFinalBean.class));
initBeanFactory(false, ConfigWithFinalBean.class));
}
@Test
void finalBeanMethodWithoutProxy() {
initBeanFactory(ConfigWithFinalBeanWithoutProxy.class);
initBeanFactory(false, ConfigWithFinalBeanWithoutProxy.class);
}
@Test // gh-31007
void voidBeanMethod() {
assertThatExceptionOfType(BeanDefinitionParsingException.class).isThrownBy(() ->
initBeanFactory(ConfigWithVoidBean.class));
initBeanFactory(false, ConfigWithVoidBean.class));
}
@Test
void simplestPossibleConfig() {
BeanFactory factory = initBeanFactory(SimplestPossibleConfig.class);
BeanFactory factory = initBeanFactory(false, SimplestPossibleConfig.class);
String stringBean = factory.getBean("stringBean", String.class);
assertThat(stringBean).isEqualTo("foo");
}
@Test
void configWithObjectReturnType() {
BeanFactory factory = initBeanFactory(ConfigWithNonSpecificReturnTypes.class);
BeanFactory factory = initBeanFactory(false, ConfigWithNonSpecificReturnTypes.class);
assertThat(factory.getType("stringBean")).isEqualTo(Object.class);
assertThat(factory.isTypeMatch("stringBean", String.class)).isFalse();
String stringBean = factory.getBean("stringBean", String.class);
@@ -173,7 +173,7 @@ class ConfigurationClassProcessingTests {
@Test
void configWithFactoryBeanReturnType() {
ListableBeanFactory factory = initBeanFactory(ConfigWithNonSpecificReturnTypes.class);
ListableBeanFactory factory = initBeanFactory(false, ConfigWithNonSpecificReturnTypes.class);
assertThat(factory.getType("factoryBean")).isEqualTo(List.class);
assertThat(factory.isTypeMatch("factoryBean", List.class)).isTrue();
assertThat(factory.getType("&factoryBean")).isEqualTo(FactoryBean.class);
@@ -201,7 +201,7 @@ class ConfigurationClassProcessingTests {
@Test
void configurationWithPrototypeScopedBeans() {
BeanFactory factory = initBeanFactory(ConfigWithPrototypeBean.class);
BeanFactory factory = initBeanFactory(false, ConfigWithPrototypeBean.class);
TestBean foo = factory.getBean("foo", TestBean.class);
ITestBean bar = factory.getBean("bar", ITestBean.class);
@@ -213,7 +213,7 @@ class ConfigurationClassProcessingTests {
@Test
void configurationWithNullReference() {
BeanFactory factory = initBeanFactory(ConfigWithNullReference.class);
BeanFactory factory = initBeanFactory(false, ConfigWithNullReference.class);
TestBean foo = factory.getBean("foo", TestBean.class);
assertThat(factory.getBean("bar")).isEqualTo(null);
@@ -223,7 +223,15 @@ class ConfigurationClassProcessingTests {
@Test // gh-33330
void configurationWithMethodNameMismatch() {
assertThatExceptionOfType(BeanDefinitionOverrideException.class)
.isThrownBy(() -> initBeanFactory(ConfigWithMethodNameMismatch.class));
.isThrownBy(() -> initBeanFactory(false, ConfigWithMethodNameMismatch.class));
}
@Test // gh-33920
void configurationWithMethodNameMismatchAndOverridingAllowed() {
BeanFactory factory = initBeanFactory(true, ConfigWithMethodNameMismatch.class);
SpousyTestBean foo = factory.getBean("foo", SpousyTestBean.class);
assertThat(foo.getName()).isEqualTo("foo1");
}
@Test
@@ -353,13 +361,13 @@ class ConfigurationClassProcessingTests {
* When complete, the factory is ready to service requests for any {@link Bean} methods
* declared by {@code configClasses}.
*/
private DefaultListableBeanFactory initBeanFactory(Class<?>... configClasses) {
private DefaultListableBeanFactory initBeanFactory(boolean allowOverriding, Class<?>... configClasses) {
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
for (Class<?> configClass : configClasses) {
String configBeanName = configClass.getName();
factory.registerBeanDefinition(configBeanName, new RootBeanDefinition(configClass));
}
factory.setAllowBeanDefinitionOverriding(false);
factory.setAllowBeanDefinitionOverriding(allowOverriding);
ConfigurationClassPostProcessor ccpp = new ConfigurationClassPostProcessor();
ccpp.postProcessBeanDefinitionRegistry(factory);
ccpp.postProcessBeanFactory(factory);
@@ -537,12 +545,12 @@ class ConfigurationClassProcessingTests {
@Configuration
static class ConfigWithMethodNameMismatch {
@Bean(name = "foo") public TestBean foo() {
return new SpousyTestBean("foo");
@Bean(name = "foo") public TestBean foo1() {
return new SpousyTestBean("foo1");
}
@Bean(name = "foo") public TestBean fooX() {
return new SpousyTestBean("fooX");
@Bean(name = "foo") public TestBean foo2() {
return new SpousyTestBean("foo2");
}
}
@@ -66,8 +66,10 @@ import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor;
import org.springframework.context.annotation.ContextAnnotationAutowireCandidateResolver;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.context.testfixture.context.annotation.AutowiredCglibConfiguration;
import org.springframework.context.testfixture.context.annotation.AutowiredComponent;
import org.springframework.context.testfixture.context.annotation.AutowiredGenericTemplate;
import org.springframework.context.testfixture.context.annotation.AutowiredMixedCglibConfiguration;
import org.springframework.context.testfixture.context.annotation.CglibConfiguration;
import org.springframework.context.testfixture.context.annotation.ConfigurableCglibConfiguration;
import org.springframework.context.testfixture.context.annotation.GenericTemplateConfiguration;
@@ -82,6 +84,7 @@ import org.springframework.context.testfixture.context.annotation.LazyResourceMe
import org.springframework.context.testfixture.context.annotation.PropertySourceConfiguration;
import org.springframework.context.testfixture.context.annotation.QualifierConfiguration;
import org.springframework.context.testfixture.context.annotation.ResourceComponent;
import org.springframework.context.testfixture.context.annotation.ValueCglibConfiguration;
import org.springframework.context.testfixture.context.generator.SimpleComponent;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
@@ -436,12 +439,14 @@ class ApplicationContextAotGeneratorTests {
@CompileWithForkedClassLoader
class ConfigurationClassCglibProxy {
private static final String CGLIB_CONFIGURATION_CLASS_SUFFIX = "$$SpringCGLIB$$0";
@Test
void processAheadOfTimeWhenHasCglibProxyWriteProxyAndGenerateReflectionHints() throws IOException {
GenericApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.registerBean(CglibConfiguration.class);
TestGenerationContext context = processAheadOfTime(applicationContext);
isRegisteredCglibClass(context, CglibConfiguration.class.getName() + "$$SpringCGLIB$$0");
isRegisteredCglibClass(context, CglibConfiguration.class.getName() + CGLIB_CONFIGURATION_CLASS_SUFFIX);
isRegisteredCglibClass(context, CglibConfiguration.class.getName() + "$$SpringCGLIB$$FastClass$$0");
isRegisteredCglibClass(context, CglibConfiguration.class.getName() + "$$SpringCGLIB$$FastClass$$1");
}
@@ -453,6 +458,43 @@ class ApplicationContextAotGeneratorTests {
.withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(context.getRuntimeHints());
}
@Test
void processAheadOfTimeExposeUserClassForCglibProxy() {
GenericApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.registerBean("config", ValueCglibConfiguration.class);
testCompiledResult(applicationContext, (initializer, compiled) -> {
GenericApplicationContext freshApplicationContext = toFreshApplicationContext(initializer);
assertThat(freshApplicationContext).satisfies(hasBeanDefinitionOfBeanClass("config", ValueCglibConfiguration.class));
assertThat(compiled.getSourceFile(".*ValueCglibConfiguration__BeanDefinitions"))
.contains("new RootBeanDefinition(ValueCglibConfiguration.class)")
.contains("new %s(".formatted(toCglibClassSimpleName(ValueCglibConfiguration.class)));
});
}
@Test
void processAheadOfTimeUsesCglibClassForFactoryMethod() {
GenericApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.registerBean("config", CglibConfiguration.class);
testCompiledResult(applicationContext, (initializer, compiled) -> {
GenericApplicationContext freshApplicationContext = toFreshApplicationContext(initializer);
assertThat(freshApplicationContext).satisfies(hasBeanDefinitionOfBeanClass("config", CglibConfiguration.class));
assertThat(compiled.getSourceFile(".*CglibConfiguration__BeanDefinitions"))
.contains("new RootBeanDefinition(CglibConfiguration.class)")
.contains(">forFactoryMethod(%s.class,".formatted(toCglibClassSimpleName(CglibConfiguration.class)))
.doesNotContain(">forFactoryMethod(%s.class,".formatted(CglibConfiguration.class));
});
}
private Consumer<GenericApplicationContext> hasBeanDefinitionOfBeanClass(String name, Class<?> beanClass) {
return context -> {
assertThat(context.containsBean(name)).isTrue();
assertThat(context.getBeanDefinition(name)).isInstanceOfSatisfying(RootBeanDefinition.class,
rbd -> assertThat(rbd.getBeanClass()).isEqualTo(beanClass));
};
}
@Test
void processAheadOfTimeWhenHasCglibProxyUseProxy() {
GenericApplicationContext applicationContext = new AnnotationConfigApplicationContext();
@@ -464,6 +506,47 @@ class ApplicationContextAotGeneratorTests {
});
}
@Test
void processAheadOfTimeWhenHasCglibProxyAndAutowiring() {
GenericApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.registerBean(AutowiredCglibConfiguration.class);
testCompiledResult(applicationContext, (initializer, compiled) -> {
GenericApplicationContext freshApplicationContext = toFreshApplicationContext(context -> {
context.setEnvironment(new MockEnvironment().withProperty("hello", "Hi"));
initializer.initialize(context);
});
assertThat(freshApplicationContext.getBean("text", String.class)).isEqualTo("Hi World");
});
}
@Test
void processAheadOfTimeWhenHasCglibProxyAndMixedAutowiring() {
GenericApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.registerBean(AutowiredMixedCglibConfiguration.class);
testCompiledResult(applicationContext, (initializer, compiled) -> {
GenericApplicationContext freshApplicationContext = toFreshApplicationContext(context -> {
context.setEnvironment(new MockEnvironment().withProperty("hello", "Hi")
.withProperty("world", "AOT World"));
initializer.initialize(context);
});
assertThat(freshApplicationContext.getBean("text", String.class)).isEqualTo("Hi AOT World");
});
}
@Test
void processAheadOfTimeWhenHasCglibProxyWithAnnotationsOnTheUserClasConstructor() {
GenericApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.registerBean("config", ValueCglibConfiguration.class);
testCompiledResult(applicationContext, (initializer, compiled) -> {
GenericApplicationContext freshApplicationContext = toFreshApplicationContext(context -> {
context.setEnvironment(new MockEnvironment().withProperty("name", "AOT World"));
initializer.initialize(context);
});
assertThat(freshApplicationContext.getBean(ValueCglibConfiguration.class)
.getName()).isEqualTo("AOT World");
});
}
@Test
void processAheadOfTimeWhenHasCglibProxyWithArgumentsUseProxy() {
GenericApplicationContext applicationContext = new AnnotationConfigApplicationContext();
@@ -487,6 +570,10 @@ class ApplicationContextAotGeneratorTests {
.accepts(generationContext.getRuntimeHints());
}
private String toCglibClassSimpleName(Class<?> configClass) {
return configClass.getSimpleName() + CGLIB_CONFIGURATION_CLASS_SUFFIX;
}
}
@Nested
@@ -213,8 +213,8 @@ class ApplicationListenerMethodAdapterTests extends AbstractApplicationEventList
@Test
void invokeListenerWithWrongGenericPayload() {
Method method = ReflectionUtils.findMethod
(SampleEvents.class, "handleGenericStringPayload", EntityWrapper.class);
Method method = ReflectionUtils.findMethod(
SampleEvents.class, "handleGenericStringPayload", EntityWrapper.class);
EntityWrapper<Integer> payload = new EntityWrapper<>(123);
invokeListener(method, new PayloadApplicationEvent<>(this, payload));
verify(this.sampleEvents, times(0)).handleGenericStringPayload(any());
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -47,7 +47,7 @@ public class EventCollector {
/**
* Return the events that the specified listener has received. The list of events
* is ordered according to their reception order.
* is ordered according to the order in which they were received.
*/
public List<Object> getEvents(Identifiable listener) {
return this.content.get(listener.getId());
@@ -67,7 +67,7 @@ class ConversionServiceFactoryBeanTests {
converters.add(new ConverterFactory<String, Bar>() {
@Override
public <T extends Bar> Converter<String, T> getConverter(Class<T> targetType) {
return new Converter<> () {
return new Converter<>() {
@SuppressWarnings("unchecked")
@Override
public T convert(String source) {
@@ -42,7 +42,7 @@ import static org.springframework.format.annotation.DurationFormat.Style.SIMPLE;
class DurationFormatterUtilsTests {
@ParameterizedTest
@EnumSource(DurationFormat.Style.class)
@EnumSource
void parseEmptyStringFailsWithDedicatedException(DurationFormat.Style style) {
assertThatIllegalArgumentException()
.isThrownBy(() -> DurationFormatterUtils.parse("", style))
@@ -50,7 +50,7 @@ class DurationFormatterUtilsTests {
}
@ParameterizedTest
@EnumSource(DurationFormat.Style.class)
@EnumSource
void parseNullStringFailsWithDedicatedException(DurationFormat.Style style) {
assertThatIllegalArgumentException()
.isThrownBy(() -> DurationFormatterUtils.parse(null, style))
@@ -113,29 +113,30 @@ class DurationFormatterUtilsTests {
@Test
void parseIsoNoChronoUnit() {
//these are based on the examples given in Duration.parse
// "PT20.345S" -- parses as "20.345 seconds"
// These are based on the examples given in Duration.parse.
// "PT20.345S" -- parses as "20.345 seconds"
assertThat(DurationFormatterUtils.parse("PT20.345S", ISO8601))
.hasMillis(20345);
// "PT15M" -- parses as "15 minutes" (where a minute is 60 seconds)
// "PT15M" -- parses as "15 minutes" (where a minute is 60 seconds)
assertThat(DurationFormatterUtils.parse("PT15M", ISO8601))
.hasSeconds(15*60);
// "PT10H" -- parses as "10 hours" (where an hour is 3600 seconds)
// "PT10H" -- parses as "10 hours" (where an hour is 3600 seconds)
assertThat(DurationFormatterUtils.parse("PT10H", ISO8601))
.hasHours(10);
// "P2D" -- parses as "2 days" (where a day is 24 hours or 86400 seconds)
// "P2D" -- parses as "2 days" (where a day is 24 hours or 86400 seconds)
assertThat(DurationFormatterUtils.parse("P2D", ISO8601))
.hasDays(2);
// "P2DT3H4M" -- parses as "2 days, 3 hours and 4 minutes"
// "P2DT3H4M" -- parses as "2 days, 3 hours and 4 minutes"
assertThat(DurationFormatterUtils.parse("P2DT3H4M", ISO8601))
.isEqualTo(Duration.ofDays(2).plusHours(3).plusMinutes(4));
// "PT-6H3M" -- parses as "-6 hours and +3 minutes"
// "PT-6H3M" -- parses as "-6 hours and +3 minutes"
assertThat(DurationFormatterUtils.parse("PT-6H3M", ISO8601))
.isEqualTo(Duration.ofHours(-6).plusMinutes(3));
// "-PT6H3M" -- parses as "-6 hours and -3 minutes"
// "-PT6H3M" -- parses as "-6 hours and -3 minutes"
assertThat(DurationFormatterUtils.parse("-PT6H3M", ISO8601))
.isEqualTo(Duration.ofHours(-6).plusMinutes(-3));
// "-PT-6H+3M" -- parses as "+6 hours and -3 minutes"
// "-PT-6H+3M" -- parses as "+6 hours and -3 minutes"
assertThat(DurationFormatterUtils.parse("-PT-6H+3M", ISO8601))
.isEqualTo(Duration.ofHours(6).plusMinutes(-3));
}
@@ -189,7 +190,7 @@ class DurationFormatterUtilsTests {
.isEqualTo(Duration.ofMinutes(34).plusSeconds(57));
}
@Test //Kotlin style compatibility
@Test // Kotlin style compatibility
void parseCompositeNegativeWithSpacesAndParenthesis() {
assertThat(DurationFormatterUtils.parse("-(34m 57s)", COMPOSITE))
.isEqualTo(Duration.ofMinutes(-34).plusSeconds(-57));
@@ -315,7 +316,7 @@ class DurationFormatterUtilsTests {
assertThat(DurationFormatterUtils.detect("-(1d 2h 34m 2ns)"))
.as("COMPOSITE")
.isEqualTo(COMPOSITE);
.isEqualTo(COMPOSITE);
assertThatIllegalArgumentException().isThrownBy(() -> DurationFormatterUtils.detect("WPT2H-4M"))
.withMessage("'WPT2H-4M' is not a valid duration, cannot detect any known style")
@@ -175,8 +175,7 @@ class ScheduledAnnotationBeanPostProcessorObservabilityTests {
}
private TestObservationRegistryAssert.TestObservationRegistryAssertReturningObservationContextAssert assertThatTaskObservation() {
return TestObservationRegistryAssert.assertThat(this.observationRegistry)
.hasObservationWithNameEqualTo("tasks.scheduled.execution").that();
return assertThat(this.observationRegistry).hasObservationWithNameEqualTo("tasks.scheduled.execution").that();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -173,6 +173,17 @@ class ScheduledAnnotationReactiveSupportTests {
assertThat(p).hasToString("checkpoint(\"@Scheduled 'mono()' in 'org.springframework.scheduling.annotation.ScheduledAnnotationReactiveSupportTests$ReactiveMethods'\")");
}
@Test
void shouldProvideToString() {
ReactiveMethods target = new ReactiveMethods();
Method m = ReflectionUtils.findMethod(ReactiveMethods.class, "mono");
Scheduled cron = AnnotationUtils.synthesizeAnnotation(Map.of("cron", "-"), Scheduled.class, null);
List<Runnable> tracker = new ArrayList<>();
assertThat(createSubscriptionRunnable(m, target, cron, () -> ObservationRegistry.NOOP, tracker))
.hasToString("org.springframework.scheduling.annotation.ScheduledAnnotationReactiveSupportTests$ReactiveMethods.mono");
}
static class ReactiveMethods {
@@ -125,7 +125,7 @@ abstract class AbstractSchedulingTaskExecutorTests {
}
@Test
@SuppressWarnings({ "deprecation", "removal" })
@SuppressWarnings("removal")
void submitListenableRunnable() {
TestTask task = new TestTask(this.testName, 1);
// Act
@@ -156,7 +156,7 @@ abstract class AbstractSchedulingTaskExecutorTests {
}
@Test
@SuppressWarnings({ "deprecation", "removal" })
@SuppressWarnings("removal")
void submitFailingListenableRunnable() {
TestTask task = new TestTask(this.testName, 0);
org.springframework.util.concurrent.ListenableFuture<?> future = executor.submitListenable(task);
@@ -185,7 +185,7 @@ abstract class AbstractSchedulingTaskExecutorTests {
}
@Test
@SuppressWarnings({ "deprecation", "removal" })
@SuppressWarnings("removal")
void submitListenableRunnableWithGetAfterShutdown() throws Exception {
org.springframework.util.concurrent.ListenableFuture<?> future1 = executor.submitListenable(new TestTask(this.testName, -1));
org.springframework.util.concurrent.ListenableFuture<?> future2 = executor.submitListenable(new TestTask(this.testName, -1));
@@ -209,18 +209,10 @@ abstract class AbstractSchedulingTaskExecutorTests {
CompletableFuture<?> future1 = executor.submitCompletable(new TestTask(this.testName, -1));
CompletableFuture<?> future2 = executor.submitCompletable(new TestTask(this.testName, -1));
shutdownExecutor();
try {
assertThatExceptionOfType(TimeoutException.class).isThrownBy(() -> {
future1.get(1000, TimeUnit.MILLISECONDS);
}
catch (Exception ex) {
// ignore
}
Awaitility.await()
.atMost(5, TimeUnit.SECONDS)
.pollInterval(10, TimeUnit.MILLISECONDS)
.untilAsserted(() -> assertThatExceptionOfType(TimeoutException.class)
.isThrownBy(() -> future2.get(1000, TimeUnit.MILLISECONDS)));
future2.get(1000, TimeUnit.MILLISECONDS);
});
}
@Test
@@ -260,7 +252,7 @@ abstract class AbstractSchedulingTaskExecutorTests {
}
@Test
@SuppressWarnings({ "deprecation", "removal" })
@SuppressWarnings("removal")
void submitListenableCallable() {
TestCallable task = new TestCallable(this.testName, 1);
// Act
@@ -275,7 +267,7 @@ abstract class AbstractSchedulingTaskExecutorTests {
}
@Test
@SuppressWarnings({ "deprecation", "removal" })
@SuppressWarnings("removal")
void submitFailingListenableCallable() {
TestCallable task = new TestCallable(this.testName, 0);
// Act
@@ -291,7 +283,7 @@ abstract class AbstractSchedulingTaskExecutorTests {
}
@Test
@SuppressWarnings({ "deprecation", "removal" })
@SuppressWarnings("removal")
void submitListenableCallableWithGetAfterShutdown() throws Exception {
org.springframework.util.concurrent.ListenableFuture<?> future1 = executor.submitListenable(new TestCallable(this.testName, -1));
org.springframework.util.concurrent.ListenableFuture<?> future2 = executor.submitListenable(new TestCallable(this.testName, -1));
@@ -16,8 +16,12 @@
package org.springframework.scheduling.config;
import io.micrometer.observation.tck.TestObservationRegistry;
import org.junit.jupiter.api.Test;
import org.springframework.scheduling.SchedulingAwareRunnable;
import org.springframework.scheduling.support.ScheduledMethodRunnable;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
@@ -72,6 +76,18 @@ class TaskTests {
assertThat(executionOutcome.throwable()).isInstanceOf(IllegalStateException.class);
}
@Test
void shouldDelegateToSchedulingAwareRunnable() throws Exception {
ScheduledMethodRunnable methodRunnable = new ScheduledMethodRunnable(new TestRunnable(),
TestRunnable.class.getMethod("run"), "myScheduler", TestObservationRegistry::create);
Task task = new Task(methodRunnable);
assertThat(task.getRunnable()).isInstanceOf(SchedulingAwareRunnable.class);
SchedulingAwareRunnable actual = (SchedulingAwareRunnable) task.getRunnable();
assertThat(actual.getQualifier()).isEqualTo(methodRunnable.getQualifier());
assertThat(actual.isLongLived()).isEqualTo(methodRunnable.isLongLived());
}
static class TestRunnable implements Runnable {
@@ -121,6 +121,24 @@ class DataBinderConstructTests {
assertThat(list.get(2).param1()).isEqualTo("value3");
}
@Test // gh-34145
void listBindingWithNonconsecutiveIndices() {
MapValueResolver valueResolver = new MapValueResolver(Map.of(
"dataClassList[0].param1", "value1", "dataClassList[0].param2", "true",
"dataClassList[1].param1", "value2", "dataClassList[1].param2", "true",
"dataClassList[3].param1", "value3", "dataClassList[3].param2", "true"));
DataBinder binder = initDataBinder(ListDataClass.class);
binder.construct(valueResolver);
ListDataClass dataClass = getTarget(binder);
List<DataClass> list = dataClass.dataClassList();
assertThat(list.get(0).param1()).isEqualTo("value1");
assertThat(list.get(1).param1()).isEqualTo("value2");
assertThat(list.get(3).param1()).isEqualTo("value3");
}
@Test
void mapBinding() {
MapValueResolver valueResolver = new MapValueResolver(Map.of(
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,6 +22,8 @@ import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import jakarta.validation.Constraint;
import jakarta.validation.ConstraintValidator;
@@ -31,6 +33,8 @@ import jakarta.validation.Valid;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.internal.constraintvalidators.bv.PatternValidator;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.aot.generate.GenerationContext;
import org.springframework.aot.hint.MemberCategory;
@@ -40,6 +44,7 @@ import org.springframework.beans.factory.aot.BeanRegistrationAotContribution;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RegisteredBean;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.OverridingClassLoader;
import org.springframework.lang.Nullable;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
@@ -121,6 +126,23 @@ class BeanValidationBeanRegistrationAotProcessorTests {
.withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(this.generationContext.getRuntimeHints());
}
@ParameterizedTest // gh-33936
@ValueSource(classes = {BeanWithRecursiveIterable.class, BeanWithRecursiveMap.class, BeanWithRecursiveOptional.class})
void shouldProcessRecursiveGenericsWithoutInfiniteRecursion(Class<?> beanClass) {
process(beanClass);
assertThat(this.generationContext.getRuntimeHints().reflection().typeHints()).hasSize(1);
assertThat(RuntimeHintsPredicates.reflection().onType(beanClass)
.withMemberCategory(MemberCategory.DECLARED_FIELDS)).accepts(this.generationContext.getRuntimeHints());
}
@Test // gh-33940
void shouldSkipConstraintWithMissingDependency() throws Exception {
MissingDependencyClassLoader classLoader = new MissingDependencyClassLoader(getClass().getClassLoader());
Class<?> beanClass = classLoader.loadClass(ConstraintWithMissingDependency.class.getName());
process(beanClass);
assertThat(this.generationContext.getRuntimeHints().reflection().typeHints()).isEmpty();
}
private void process(Class<?> beanClass) {
BeanRegistrationAotContribution contribution = createContribution(beanClass);
if (contribution != null) {
@@ -244,4 +266,43 @@ class BeanValidationBeanRegistrationAotProcessorTests {
}
}
static class BeanWithRecursiveIterable {
Iterable<BeanWithRecursiveIterable> iterable;
}
static class BeanWithRecursiveMap {
Map<BeanWithRecursiveMap, BeanWithRecursiveMap> map;
}
static class BeanWithRecursiveOptional {
Optional<BeanWithRecursiveOptional> optional;
}
static class ConstraintWithMissingDependency {
MissingType missingType;
}
static class MissingType {}
static class MissingDependencyClassLoader extends OverridingClassLoader {
MissingDependencyClassLoader(ClassLoader parent) {
super(parent);
}
@Override
protected boolean isEligibleForOverriding(String className) {
return className.startsWith(BeanValidationBeanRegistrationAotProcessorTests.class.getName());
}
@Override
protected Class<?> loadClassForOverriding(String name) throws ClassNotFoundException {
if (name.contains("MissingType")) {
throw new NoClassDefFoundError(name);
}
return super.loadClassForOverriding(name);
}
}
}
@@ -0,0 +1,35 @@
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.testfixture.context.annotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
@Configuration
public class AutowiredCglibConfiguration {
@Autowired
private Environment environment;
@Bean
public String text() {
return this.environment.getProperty("hello") + " World";
}
}
@@ -0,0 +1,41 @@
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.testfixture.context.annotation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
@Configuration
public class AutowiredMixedCglibConfiguration {
@Value("${world:World}")
private String world;
private final Environment environment;
public AutowiredMixedCglibConfiguration(Environment environment) {
this.environment = environment;
}
@Bean
public String text() {
return this.environment.getProperty("hello") + " " + this.world;
}
}
@@ -0,0 +1,34 @@
/*
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context.testfixture.context.annotation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ValueCglibConfiguration {
private final String name;
public ValueCglibConfiguration(@Value("${name:World}") String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -124,6 +124,14 @@ public enum MemberCategory {
* reflection for inner classes but rather makes sure they are available
* via a call to {@link Class#getDeclaredClasses}.
*/
DECLARED_CLASSES
DECLARED_CLASSES,
/**
* A category that represents the need for
* {@link sun.misc.Unsafe#allocateInstance(Class) unsafe allocation}
* for this type.
* @since 6.2.1
*/
UNSAFE_ALLOCATED
}
@@ -124,6 +124,7 @@ class ReflectionHintsWriter {
attributes.put("allDeclaredMethods", true);
case PUBLIC_CLASSES -> attributes.put("allPublicClasses", true);
case DECLARED_CLASSES -> attributes.put("allDeclaredClasses", true);
case UNSAFE_ALLOCATED -> attributes.put("unsafeAllocated", true);
}
}
);
@@ -44,7 +44,6 @@ import kotlinx.coroutines.reactor.ReactorFlowKt;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.SynchronousSink;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
@@ -109,7 +108,7 @@ public abstract class CoroutinesUtils {
* @throws IllegalArgumentException if {@code method} is not a suspending function
* @since 6.0
*/
@SuppressWarnings({"deprecation", "DataFlowIssue", "NullAway"})
@SuppressWarnings({"DataFlowIssue", "NullAway"})
public static Publisher<?> invokeSuspendingFunction(
CoroutineContext context, Method method, @Nullable Object target, @Nullable Object... args) {
@@ -146,7 +145,7 @@ public abstract class CoroutinesUtils {
}
return KCallables.callSuspendBy(function, argMap, continuation);
})
.handle(CoroutinesUtils::handleResult)
.filter(result -> result != Unit.INSTANCE)
.onErrorMap(InvocationTargetException.class, InvocationTargetException::getTargetException);
KType returnType = function.getReturnType();
@@ -166,22 +165,4 @@ public abstract class CoroutinesUtils {
return ReactorFlowKt.asFlux(((Flow<?>) flow));
}
private static void handleResult(Object result, SynchronousSink<Object> sink) {
if (result == Unit.INSTANCE) {
sink.complete();
}
else if (KotlinDetector.isInlineClass(result.getClass())) {
try {
sink.next(result.getClass().getDeclaredMethod("unbox-impl").invoke(result));
sink.complete();
}
catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException ex) {
sink.error(ex);
}
}
else {
sink.next(result);
sink.complete();
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2024 the original author or authors.
* Copyright 2002-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -180,7 +180,7 @@ public final class GenericTypeResolver {
generics[i] = resolvedTypeArgument;
}
else {
generics[i] = ResolvableType.forType(typeArgument);
generics[i] = ResolvableType.forType(typeArgument).resolveType();
}
}
else if (typeArgument instanceof ParameterizedType) {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2024 the original author or authors.
* Copyright 2002-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -334,19 +334,19 @@ public class ResolvableType implements Serializable {
// Deal with wildcard bounds
WildcardBounds ourBounds = WildcardBounds.get(this);
WildcardBounds typeBounds = WildcardBounds.get(other);
WildcardBounds otherBounds = WildcardBounds.get(other);
// In the form X is assignable to <? extends Number>
if (typeBounds != null) {
if (otherBounds != null) {
if (ourBounds != null) {
return (ourBounds.isSameKind(typeBounds) &&
ourBounds.isAssignableFrom(typeBounds.getBounds(), matchedBefore));
return (ourBounds.isSameKind(otherBounds) &&
ourBounds.isAssignableFrom(otherBounds.getBounds(), matchedBefore));
}
else if (upUntilUnresolvable) {
return typeBounds.isAssignableFrom(this, matchedBefore);
return otherBounds.isAssignableFrom(this, matchedBefore);
}
else if (!exactMatch) {
return typeBounds.isAssignableTo(this, matchedBefore);
return otherBounds.isAssignableTo(this, matchedBefore);
}
else {
return false;
@@ -400,8 +400,8 @@ public class ResolvableType implements Serializable {
if (checkGenerics) {
// Recursively check each generic
ResolvableType[] ourGenerics = getGenerics();
ResolvableType[] typeGenerics = other.as(ourResolved).getGenerics();
if (ourGenerics.length != typeGenerics.length) {
ResolvableType[] otherGenerics = other.as(ourResolved).getGenerics();
if (ourGenerics.length != otherGenerics.length) {
return false;
}
if (ourGenerics.length > 0) {
@@ -410,7 +410,9 @@ public class ResolvableType implements Serializable {
}
matchedBefore.put(this.type, other.type);
for (int i = 0; i < ourGenerics.length; i++) {
if (!ourGenerics[i].isAssignableFrom(typeGenerics[i], true, matchedBefore, upUntilUnresolvable)) {
ResolvableType otherGeneric = otherGenerics[i];
if (!ourGenerics[i].isAssignableFrom(otherGeneric,
!otherGeneric.isUnresolvableTypeVariable(), matchedBefore, upUntilUnresolvable)) {
return false;
}
}
@@ -1728,8 +1730,16 @@ public class ResolvableType implements Serializable {
* @return {@code true} if these bounds are assignable from all types
*/
public boolean isAssignableFrom(ResolvableType[] types, @Nullable Map<Type, Type> matchedBefore) {
for (ResolvableType type : types) {
if (!isAssignableFrom(type, matchedBefore)) {
for (ResolvableType bound : this.bounds) {
boolean matched = false;
for (ResolvableType type : types) {
if (this.kind == Kind.UPPER ? bound.isAssignableFrom(type, false, matchedBefore, false) :
type.isAssignableFrom(bound, false, matchedBefore, false)) {
matched = true;
break;
}
}
if (!matched) {
return false;
}
}
@@ -34,7 +34,6 @@ import org.springframework.lang.Contract;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
/**
* Contextual descriptor about a type to convert from or to.
@@ -501,16 +500,7 @@ public class TypeDescriptor implements Serializable {
if (!annotationsMatch(otherDesc)) {
return false;
}
if (isCollection() || isArray()) {
return ObjectUtils.nullSafeEquals(getElementTypeDescriptor(), otherDesc.getElementTypeDescriptor());
}
else if (isMap()) {
return (ObjectUtils.nullSafeEquals(getMapKeyTypeDescriptor(), otherDesc.getMapKeyTypeDescriptor()) &&
ObjectUtils.nullSafeEquals(getMapValueTypeDescriptor(), otherDesc.getMapValueTypeDescriptor()));
}
else {
return Arrays.equals(getResolvableType().getGenerics(), otherDesc.getResolvableType().getGenerics());
}
return Arrays.equals(getResolvableType().getGenerics(), otherDesc.getResolvableType().getGenerics());
}
private boolean annotationsMatch(TypeDescriptor otherDesc) {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2024 the original author or authors.
* Copyright 2002-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -40,6 +40,7 @@ import java.nio.file.Path;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.NavigableSet;
@@ -645,13 +646,15 @@ public class PathMatchingResourcePatternResolver implements ResourcePatternResol
}
}
if (currentPrefix != null) {
// A prefix match found, potentially to be turned into a common parent cache entry.
if (commonPrefix == null || !commonUnique || currentPrefix.length() > commonPrefix.length()) {
commonPrefix = currentPrefix;
existingPath = path;
}
else if (currentPrefix.equals(commonPrefix)) {
commonUnique = false;
if (checkPathWithinPackage(path.substring(currentPrefix.length()))) {
// A prefix match found, potentially to be turned into a common parent cache entry.
if (commonPrefix == null || !commonUnique || currentPrefix.length() > commonPrefix.length()) {
commonPrefix = currentPrefix;
existingPath = path;
}
else if (currentPrefix.equals(commonPrefix)) {
commonUnique = false;
}
}
}
else if (actualRootPath == null || path.length() > actualRootPath.length()) {
@@ -804,7 +807,7 @@ public class PathMatchingResourcePatternResolver implements ResourcePatternResol
if (separatorIndex == -1) {
separatorIndex = urlFile.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
}
if (separatorIndex != -1) {
if (separatorIndex >= 0) {
jarFileUrl = urlFile.substring(0, separatorIndex);
rootEntryPath = urlFile.substring(separatorIndex + 2); // both separators are 2 chars
NavigableSet<String> entriesCache = this.jarEntriesCache.get(jarFileUrl);
@@ -831,11 +834,17 @@ public class PathMatchingResourcePatternResolver implements ResourcePatternResol
if (con instanceof JarURLConnection jarCon) {
// Should usually be the case for traditional JAR files.
jarFile = jarCon.getJarFile();
jarFileUrl = jarCon.getJarFileURL().toExternalForm();
JarEntry jarEntry = jarCon.getJarEntry();
rootEntryPath = (jarEntry != null ? jarEntry.getName() : "");
closeJarFile = !jarCon.getUseCaches();
try {
jarFile = jarCon.getJarFile();
jarFileUrl = jarCon.getJarFileURL().toExternalForm();
JarEntry jarEntry = jarCon.getJarEntry();
rootEntryPath = (jarEntry != null ? jarEntry.getName() : "");
closeJarFile = !jarCon.getUseCaches();
}
catch (FileNotFoundException ex) {
// Happens in case of cached root directory without specific subdirectory present.
return Collections.emptySet();
}
}
else {
// No JarURLConnection -> need to resort to URL file parsing.
@@ -872,7 +881,13 @@ public class PathMatchingResourcePatternResolver implements ResourcePatternResol
}
Set<Resource> result = new LinkedHashSet<>(64);
NavigableSet<String> entriesCache = new TreeSet<>();
for (String entryPath : jarFile.stream().map(JarEntry::getName).sorted().toList()) {
Iterator<String> entryIterator = jarFile.stream().map(JarEntry::getName).sorted().iterator();
while (entryIterator.hasNext()) {
String entryPath = entryIterator.next();
int entrySeparatorIndex = entryPath.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
if (entrySeparatorIndex >= 0) {
entryPath = entryPath.substring(entrySeparatorIndex + ResourceUtils.JAR_URL_SEPARATOR.length());
}
entriesCache.add(entryPath);
if (entryPath.startsWith(rootEntryPath)) {
String relativePath = entryPath.substring(rootEntryPath.length());
@@ -978,8 +993,8 @@ public class PathMatchingResourcePatternResolver implements ResourcePatternResol
}
if (!Files.exists(rootPath)) {
if (logger.isInfoEnabled()) {
logger.info("Skipping search for files matching pattern [%s]: directory [%s] does not exist"
if (logger.isDebugEnabled()) {
logger.debug("Skipping search for files matching pattern [%s]: directory [%s] does not exist"
.formatted(subPattern, rootPath.toAbsolutePath()));
}
return result;
@@ -1103,6 +1118,10 @@ public class PathMatchingResourcePatternResolver implements ResourcePatternResol
return (path.startsWith("/") ? path.substring(1) : path);
}
private static boolean checkPathWithinPackage(String path) {
return (path.contains("/") && !path.contains(ResourceUtils.JAR_URL_SEPARATOR));
}
/**
* Inner delegate class, avoiding a hard JBoss VFS API dependency at runtime.
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -51,10 +51,11 @@ public class FlightRecorderApplicationStartup implements ApplicationStartup {
@Override
public StartupStep start(String name) {
Long parentId = this.currentSteps.getFirst();
long sequenceId = this.currentSequenceId.incrementAndGet();
this.currentSteps.offerFirst(sequenceId);
return new FlightRecorderStartupStep(sequenceId, name,
this.currentSteps.getFirst(), committedStep -> this.currentSteps.removeFirstOccurrence(sequenceId));
parentId, committedStep -> this.currentSteps.removeFirstOccurrence(sequenceId));
}
}
@@ -26,7 +26,9 @@ import java.util.function.Consumer;
import org.springframework.lang.Nullable;
/**
* Composite map that combines two other maps. This type is created via
* Composite map that combines two other maps.
*
* <p>This type is created via
* {@link CollectionUtils#compositeMap(Map, Map, BiFunction, Consumer)}.
*
* @author Arjen Poutsma
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -98,13 +98,11 @@ public class FastByteArrayOutputStream extends OutputStream {
if (this.closed) {
throw new IOException("Stream closed");
}
else {
if (this.buffers.peekLast() == null || this.buffers.getLast().length == this.index) {
addBuffer(1);
}
// store the byte
this.buffers.getLast()[this.index++] = (byte) datum;
if (this.buffers.peekLast() == null || this.buffers.getLast().length == this.index) {
addBuffer(1);
}
// store the byte
this.buffers.getLast()[this.index++] = (byte) datum;
}
@Override
@@ -384,22 +382,20 @@ public class FastByteArrayOutputStream extends OutputStream {
// This stream doesn't have any data in it...
return -1;
}
if (this.nextIndexInCurrentBuffer < this.currentBufferLength) {
this.totalBytesRead++;
return this.currentBuffer[this.nextIndexInCurrentBuffer++] & 0xFF;
}
else {
if (this.nextIndexInCurrentBuffer < this.currentBufferLength) {
this.totalBytesRead++;
return this.currentBuffer[this.nextIndexInCurrentBuffer++] & 0xFF;
if (this.buffersIterator.hasNext()) {
this.currentBuffer = this.buffersIterator.next();
updateCurrentBufferLength();
this.nextIndexInCurrentBuffer = 0;
}
else {
if (this.buffersIterator.hasNext()) {
this.currentBuffer = this.buffersIterator.next();
updateCurrentBufferLength();
this.nextIndexInCurrentBuffer = 0;
}
else {
this.currentBuffer = null;
}
return read();
this.currentBuffer = null;
}
return read();
}
}
@@ -23,8 +23,9 @@ import java.util.function.Predicate;
import org.springframework.lang.Nullable;
/**
* Iterator that filters out values that do not match a predicate.
* This type is used by {@link CompositeMap}.
* {@link Iterator} that filters out values that do not match a predicate.
*
* <p>This type is used by {@link CompositeMap}.
*
* @author Arjen Poutsma
* @since 6.2
@@ -39,7 +40,7 @@ final class FilteredIterator<E> implements Iterator<E> {
@Nullable
private E next;
private boolean nextSet;
private boolean hasNext;
public FilteredIterator(Iterator<E> delegate, Predicate<E> filter) {
@@ -52,22 +53,15 @@ final class FilteredIterator<E> implements Iterator<E> {
@Override
public boolean hasNext() {
if (this.nextSet) {
return true;
}
else {
return setNext();
}
return (this.hasNext || setNext());
}
@Override
public E next() {
if (!this.nextSet) {
if (!setNext()) {
throw new NoSuchElementException();
}
if (!this.hasNext && !setNext()) {
throw new NoSuchElementException();
}
this.nextSet = false;
this.hasNext = false;
Assert.state(this.next != null, "Next should not be null");
return this.next;
}
@@ -77,7 +71,7 @@ final class FilteredIterator<E> implements Iterator<E> {
E next = this.delegate.next();
if (this.filter.test(next)) {
this.next = next;
this.nextSet = true;
this.hasNext = true;
return true;
}
}

Some files were not shown because too many files have changed in this diff Show More