Compare commits

...

259 Commits

Author SHA1 Message Date
Brian Clozel cf74ce007d Release v6.2.15 2025-12-11 10:58:54 +01:00
Brian Clozel 23625ee698 Do not send null HTTP header value in JdkClientHttpRequest
Prior to this commit, the `JdkClientHttpRequest` would add all values
from `HttpHeaders` to the native request builder. This could cause
`NullPointerException` being thrown at runtime because the `HttpClient`
does not support that.

This commit replicates a fix that was applied to the
`SimpleClientHttpRequest`, turning null values into empty "".

Fixes gh-35996
2025-12-11 09:57:55 +01:00
Brian Clozel c89c4ac614 Upgrade to Reactor 2024.0.13
Closes gh-35987
2025-12-09 22:26:46 +01:00
Brian Clozel 2155e9fb25 Upgrade to Micrometer 1.14.14
Closes gh-35986
2025-12-09 22:26:10 +01:00
Juergen Hoeller 24df35c55a Do not keep target connection after failed settings
Includes aligned setReadOnly exception suppression.

Closes gh-35980

(cherry picked from commit ab33000750)
2025-12-09 13:01:36 +01:00
Brian Clozel 3b1fa369b4 Polishing contribution
Closes gh-35978
2025-12-08 16:11:38 +01:00
Johnny Lim 221adf14a4 Fix SubscriberInputStream.resume()
See gh-35978

Signed-off-by: Johnny Lim <izeye@naver.com>
2025-12-08 16:11:31 +01:00
Juergen Hoeller ad849fb3a2 Accept assignable match for covariant return type
See gh-35936

(cherry picked from commit df27627516)
2025-12-08 12:43:35 +01:00
Juergen Hoeller 8041a09268 Polishing 2025-12-05 16:23:12 +01:00
Juergen Hoeller 97b9517918 Handle absolute file URLs in getClassPathManifestEntriesFromJar
Closes gh-35682

(cherry picked from commit 196c1dd51c)
2025-12-05 16:16:44 +01:00
Sam Brannen e79d8e35a2 Document that annotations which reference types not present are ignored
Add warnings to the class-level Javadoc for MergedAnnotations,
AnnotatedTypeMetadata, AnnotationMetadata, and MethodMetadata to point
out that annotations may be ignored if their attributes reference types
that are not present in the classpath.

Closes gh-35959

(cherry picked from commit b916dc962e)
2025-12-05 16:02:14 +01:00
rstoyanchev 96503a2ea6 Polishing 2025-12-04 09:31:20 +00:00
rstoyanchev 8803d3c5dc Lower bad requests to DEBUG level in AbstractHandshakeHandler
Closes gh-35930
2025-12-04 09:24:11 +00:00
rstoyanchev 5b4728f0bf Avoid http - web.utils package cycle
Closes gh-35952
2025-12-04 09:23:45 +00:00
Juergen Hoeller 1fd1d8d629 Polishing
(cherry picked from commit 07c0213f20)
2025-12-04 00:40:02 +01:00
Juergen Hoeller afc40d7b93 Avoid computeIfAbsent for createMappings which calls back into same map
Closes gh-35944

(cherry picked from commit 667851c0fa)
2025-12-04 00:15:36 +01:00
Sam Brannen 3eb1df0ac0 Update antora-extensions to 1.14.7
Closes gh-35949

(cherry picked from commit c7e24a5c26)
2025-12-02 15:36:45 +01:00
Juergen Hoeller 2aa3b0a77e Select method with resolved return type match (among multiple candidates)
Removes unnecessary array type check for parameters of candidate methods.

Closes gh-35936

(cherry picked from commit 92e9543ad4)
2025-12-01 23:28:09 +01:00
ivonaest 0008106adb Upgrade json-path to 2.10.0
Closes gh-35924
Signed-off-by: ivonaest <ivona.cvija@est.tech>
2025-12-01 15:36:44 +01:00
Juergen Hoeller 8f6d44a86b Improve debug log for received message
(cherry picked from commit 71d18ebabc)
2025-12-01 15:04:42 +01:00
Juergen Hoeller 874498272f Clear remaining invoker resources when releasing shared Connection
Closes gh-35932

(cherry picked from commit 3ccb0786db)
2025-12-01 15:04:39 +01:00
rstoyanchev 2144813bad FragmentsRendering exposes its fragments
Closes gh-35775
2025-12-01 11:20:43 +00:00
John Niang 67a92306f7 BindingContext constructor uses given ReactiveAdapterRegistry arg
Closes gh-35771

Signed-off-by: John Niang <johnniang@foxmail.com>
2025-12-01 11:20:29 +00:00
rstoyanchev bc0731891b Use channelId for ReactorNettyWebSocketSession's id
Closes gh-35883
2025-12-01 11:20:13 +00:00
Juergen Hoeller 3faa7cac4d Polishing 2025-11-30 11:41:24 +01:00
Sam Brannen 3121daf553 Stop linking to 6.1.22-SNAPSHOT reference docs
With this commit, we now include snapshots for main (which currently
correlates to 7.0.x), 6.2.x, and 7.0.x to 9.*.x.

Closes gh-35923

(cherry picked from commit 305a512a55)
2025-11-28 14:06:48 +01:00
Juergen Hoeller 821165488e Use concurrent set for reactive transaction synchronizations
Closes gh-35921

(cherry picked from commit fd25e2f468)
2025-11-28 10:25:54 +01:00
Juergen Hoeller 3b556ba0c0 Polishing 2025-11-27 16:10:56 +01:00
Juergen Hoeller b25f98374b Tighten cacheable decision behind @Lazy injection point
Closes gh-35917

(cherry picked from commit 61d5413c23)
2025-11-27 16:03:27 +01:00
Sam Brannen c2f7cd3401 Convert sentence to tip in Kotlin testing chapter
This commit also moves the text to a more appropriate section of the
chapter.

(cherry picked from commit 24d152cdab)
2025-11-27 12:38:55 +01:00
Juergen Hoeller 22d2810ed0 Narrow method annotation check in hasQualifier to setter methods
Closes gh-35908

(cherry picked from commit 6c3132cb8c)
2025-11-26 23:02:58 +01:00
Tran Ngoc Nhan b39055f293 Fix broken Javadoc links to methods
Closes gh-35904
Signed-off-by: Tran Ngoc Nhan <ngocnhan.tran1996@gmail.com>
2025-11-26 17:12:18 +01:00
Sam Brannen 140933400d Refer to "Spring Tools" instead of "Spring Tools for Eclipse"
Closes gh-35901

(cherry picked from commit 6504177e7b)
2025-11-26 16:12:27 +01:00
Juergen Hoeller e7a5452a14 Consistent namespace element declarations
(cherry picked from commit f58d0f6aae)
2025-11-26 15:14:31 +01:00
Juergen Hoeller ab96576e67 Expose non-existent resources at the end of the sorted result
Closes gh-35895

(cherry picked from commit c1b6bfb681)
2025-11-26 15:14:28 +01:00
Juergen Hoeller 19b080b73f Clarify JMS sessionTransacted flag for local versus global transaction
Closes gh-35897

(cherry picked from commit 9d4abb63d8)
2025-11-26 15:14:24 +01:00
rstoyanchev f9b4fba97a Add required type to TypeMismatchException message args
Closes gh-35837
2025-11-26 12:50:26 +00:00
Sam Brannen 37e26e0377 Use current links to JUnit documentation
Closes gh-35892

(cherry picked from commit f4ee120a42)
2025-11-26 13:25:54 +01:00
Sam Brannen 85c47a73dd Fix formatting for backticks in Kotlin docs
(cherry picked from commit e625a28f6d)
2025-11-26 13:24:27 +01:00
Sam Brannen ab93020263 Link to Spring Framework Artifacts wiki page
This commit revises the Integration Testing chapter to reference the
"Spring Framework Artifacts" wiki page instead of the nonexistent
"Dependency Management" section of the reference manual.

Closes gh-35890

(cherry picked from commit 45c1cd9295)
2025-11-26 12:55:46 +01:00
github-actions[bot] a4134663a6 Update Antora Spring UI to v0.4.25
Closes gh-35877

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2025-11-24 14:44:14 +01:00
github-actions[bot] a4b1155ca6 Update Antora Spring UI to v0.4.22
Closes gh-35859
2025-11-24 10:14:50 +01:00
Sébastien Deleuze 1bdd8337c6 Update outdated comments in JdbcOperationsExtensions.kt 2025-11-20 09:55:10 +01:00
Brian Clozel 7a0ea14452 Next development version (v6.2.15-SNAPSHOT) 2025-11-20 09:48:06 +01:00
Juergen Hoeller 59025c5b96 Lazily initialize ProblemDetail for picking up actual status code
Closes gh-35829

(cherry picked from commit 3026f0a49b)
2025-11-19 17:31:27 +01:00
Sam Brannen e5de8b9bc6 Fix link to MockMvc test in HtmlUnit section
See gh-35853

(cherry picked from commit 9fe4e7798d)
2025-11-19 17:19:34 +01:00
Sam Brannen e146e809e5 Polishing
(cherry picked from commit d178930186)
2025-11-19 17:19:34 +01:00
Tran Ngoc Nhan ff62e7355f Fix cross-reference links in HtmlUnit sections
Closes gh-35853

Signed-off-by: Tran Ngoc Nhan <ngocnhan.tran1996@gmail.com>

(cherry picked from commit 91d2a51f3f)
2025-11-19 17:19:30 +01:00
Juergen Hoeller 4e97013595 Polishing
(cherry picked from commit f456674529)
2025-11-19 16:21:38 +01:00
Juergen Hoeller bd10b7ae06 Remove javadoc references to deprecated PropertiesBeanDefinitionReader
Closes gh-35836

(cherry picked from commit 35b8fbf901)
2025-11-19 16:21:33 +01:00
Juergen Hoeller e4288170c8 Fix getCacheNames() concurrent access in NoOpCacheManager
Closes gh-35842

(cherry picked from commit 57a1d4007b)
2025-11-18 13:50:13 +01:00
Juergen Hoeller 8545a759a7 Add resetCaches() method to Caffeine/ConcurrentMapCacheManager
Closes gh-35840

(cherry picked from commit bc3431f435)
2025-11-18 13:49:20 +01:00
Juergen Hoeller f94645de17 Narrow Aware interface exclusion check to BeanFactoryAware only
Closes gh-35835

(cherry picked from commit de5b9aab55)
2025-11-18 13:48:32 +01:00
Sam Brannen 8553f97df1 Merge HtmlCharacterEntityDecoderTests into HtmlUtilsTests
See gh-35711

(cherry picked from commit 0342cd0904)
2025-11-17 15:29:52 +01:00
Brian Clozel 030dace2be Polishing contribution
Closes gh-35477
2025-11-17 15:15:39 +01:00
potato 5af1c9b487 Fix HtmlUtils unescape for supplementary chars
See gh-35477

Signed-off-by: potato <65760583+juntae6942@users.noreply.github.com>
2025-11-17 15:15:39 +01:00
Patrick Strawderman f3ed04c9d7 Fix single-check idiom in UnmodifiableMultiValueMap
Read the respective fields only once in the values(), entrySet(), and
keySet() methods.

Closes gh-35822

Signed-off-by: Patrick Strawderman <pstrawderman@netflix.com>

(cherry picked from commit 3b6be3d4d3)
2025-11-17 15:04:49 +01:00
github-actions[bot] 46ee944acc Update Antora Spring UI to v0.4.20
Closes gh-35814
2025-11-17 14:22:35 +01:00
Sam Brannen 6be1c29fda Polish contribution
See gh-35817

(cherry picked from commit 09a8bbc0c7)
2025-11-17 12:28:03 +01:00
Patrick Strawderman 3fa56db88b Fix Spliterator characteristics in ConcurrentReferenceHashMap
The Spliterators returned by values, entrySet, and keySet incorrectly
reported the SIZED characteristic, instead of CONCURRENT. This could
lead to bugs when the map is concurrently modified during a stream
operation.

For keySet and values, the incorrect characteristics are inherited from
AbstractMap, so to rectify that the respective methods are overridden,
and custom collections are provided that report the correct Spliterator
characteristics.

Closes gh-35817

Signed-off-by: Patrick Strawderman <pstrawderman@netflix.com>

(cherry picked from commit ed75906834)
2025-11-17 12:27:43 +01:00
Brian Clozel ed444eb0c1 Next development version (v6.2.14-SNAPSHOT) 2025-11-13 10:11:35 +01:00
Brian Clozel da31750e5f Upgrade to Micrometer 1.14.13
Closes gh-35810
2025-11-13 09:15:09 +01:00
Brian Clozel b853203846 Upgrade to Reactor 2024.0.12
Closes gh-35809
2025-11-13 09:14:04 +01:00
Brian Clozel 2b04df045a Upgrade to Jetty 12.0.30
Closes gh-35806
2025-11-12 21:57:31 +01:00
Juergen Hoeller 40544e096f Fix typo in ProxyMethodInvocation javadoc 2025-11-11 19:42:02 +01:00
Juergen Hoeller 23354b0155 Fix doTask method visibility (referring to private Task type)
See gh-35794
2025-11-11 19:41:44 +01:00
Juergen Hoeller 5c5367a1be Polishing 2025-11-11 15:40:08 +01:00
Juergen Hoeller 12dd758158 Provide compute method implementations in ConcurrentReferenceHashMap
Closes gh-35794
2025-11-11 15:39:21 +01:00
Sébastien Deleuze 5aec239261 Add hints for entities package-private methods
Closes gh-35711
2025-11-11 13:52:59 +01:00
Dmitry Sulman d0ff8f9243 Fix HttpServiceMethod for suspending functions returning Flow
Closes gh-35718
Signed-off-by: Dmitry Sulman <dmitry.sulman@gmail.com>
2025-11-11 12:58:42 +01:00
Brian Clozel ba39385cce Use executor for blocking I/O in Reactor request factory
Prior to this commit, the `ReactorClientHttpRequestFactory` and the
`ReactorClientHttpRequest` would use the `Executor` from the current
event loop for performing write operations.
Depending on I/O demand, this work could be blocked and would result in
blocked Netty event loop executors and the HTTP client hanging.

This commit ensures that the client uses a separate Executor for such
operations. If the application does not provide one on the request
factory, a `Schedulers#boundedElastic` instance will be used.

Fixes gh-34707
2025-11-10 16:12:14 +01:00
rstoyanchev e735c2d9c5 Improve Filter overview in reference docs
Closes gh-30454
2025-11-10 14:43:34 +00:00
rstoyanchev 3cb498fa98 Improve docs on streaming via StreamingHttpOutputMessage
Closes gh-35700
2025-11-10 14:43:34 +00:00
Sam Brannen 335a2c4e21 Support response encoding in select and options JSP form tags
Prior to this commit, Spring Framework's JSP form tags supported the
response encoding in most places; however, <form:select> and
<form:options> still did not support the response character encoding.

To address that, this commit updates SelectTag, OptionsTag, and
OptionWriter to provide support for response character encoding in the
`select` and `options` JSP form tags.

See gh-33023
Closes gh-35783
2025-11-10 15:35:13 +01:00
Sam Brannen 1714a00492 Suppress warnings in Gradle build 2025-11-10 14:13:34 +01:00
Chandra Bhan Singh ddb45a9302 Correct documentation formatting for Mono type
Closes gh-35786
Signed-off-by: Chandra Bhan Singh <cbhansingh1@gmail.com>
2025-11-10 12:03:37 +01:00
Juergen Hoeller 38555df3d8 Fix Aware exclusion check to apply to interface method only
See gh-35780
2025-11-08 09:53:17 +01:00
Juergen Hoeller 6f81cb625c Avoid unnecessary bridge method resolution around getMostSpecificMethod
Closes gh-35780
2025-11-08 09:16:31 +01:00
Juergen Hoeller 566078b4e4 Add explicit note on empty constructor
See gh-35773
2025-11-08 09:14:53 +01:00
Brian Clozel f0cf7f19f6 Fix multi-release JAR issue with VirtualThreadDelegate
This commit ensures that both `VirtualThreadDelegate` implementations
expose the same public API. If not, JAR verification fails with the
following message:

```
jar --validate --file spring-core-6.2.13-SNAPSHOT.jar
entry: META-INF/versions/21/org/springframework/core/task/VirtualThreadDelegate.class, contains a class with different api from earlier version
```

Fixes gh-35773
2025-11-07 14:01:51 +01:00
Juergen Hoeller b5008d33ee Upgrade to ASM 9.9 plus lenient version check patch
Closes gh-35763
2025-11-06 10:41:34 +01:00
Juergen Hoeller bce1445d92 Accept fallback match for bean name or method-level qualifier as well
Closes gh-35690
2025-11-05 19:31:53 +01:00
Brian Clozel 285182be27 Relax multiple segment matching constraints in PathPattern
Prior to this commit, gh-35213 allowed wildcard path elments at the
start of path patterns. This came with an additional constraint that
rejected such patterns if the pattern segment following the wildcard one
was not a literal:

* `/**/{name}` was rejected
* `/**/something/{name}` was accepted

The motivation here was to make the performance impact of wildard
patterns as small as possible at runtime.

This commit relaxes this constraint because `/**/*.js` patterns are very
popular in the security space for request matchers.

Closes gh-35686
2025-11-05 18:32:44 +01:00
Brian Clozel 8bb63081a8 Document PathPattern matching for single/multiple segments
This commit improves the reference document to better reflect the
different between `*` or `{name}` on one side, and `**` or `{*path}` on
the other.

The former patterns only consider a single path segment and its content,
while the latter variants consider zero or more path segments. This
explains why `/test/{*path}` can match `/test`.

Closes gh-35727
2025-11-05 14:58:58 +01:00
rstoyanchev a698b1bc0d Refine validation section for controllers
Closes gh-35759
2025-11-05 12:23:43 +00:00
Juergen Hoeller 2060c340ce Upgrade to Caffeine 3.2.3, Selenium 4.38, HtmlUnit 4.18 2025-11-05 12:44:28 +01:00
Juergen Hoeller 4f97c41e58 Avoid javadoc failure for line break with annotation reference
See gh-35736
2025-11-05 12:35:09 +01:00
Juergen Hoeller 0243059f53 Polishing 2025-11-05 12:22:56 +01:00
Juergen Hoeller b027b73a7a Relax configuration class requirement in configurer callback javadoc
Closes gh-35736
2025-11-05 12:22:44 +01:00
Brian Clozel c0429dbb09 Fix file extension resolution for media types with q parameter
Prior to this commit, the `MappingMediaTypeFileExtensionResolver` would
resolve file extensions for a given media type by using a direct lookup
using the given media type provided by the request.
If the request contains a quality parameter like
"application/json;q=0.9", this would not resolve configured file
extensions for this media type.
While other media type parameters can be meaningful, the quality
parameter should not be used for lookups. This commit ensures that the
quality parameter is dropped before performing lookups.

Fixes gh-35754
2025-11-05 10:48:24 +01:00
Brian Clozel d65de19e7d Deprecate setConnectTimeout on HttpComponents client factory
Prior to this commit, the `HttpComponentsClientHttpRequestFactory` would
set the connection timeout on the request configuration. This has been
deprecated by the client itself and this value should be set while
creating the client on the connection manager itself.

This commit deprecates this method, as there is no way for the factory
to set this value anymore.

Closes gh-35748
2025-11-03 16:53:54 +01:00
Sébastien Deleuze 16822c2fd0 Polishing
Closes gh-35746
2025-11-03 11:14:30 +01:00
Moad Elfatihi 983d39a970 Update CI documentation reference in README
Replace obsolete Concourse pipeline reference with GitHub Actions.
The Concourse link returns 404.

See gh-35746
Signed-off-by: Moad ELFATIHI <elfatihi.moad@gmail.com>
2025-11-03 11:14:14 +01:00
Juergen Hoeller 4b7cf85d71 Retrieve cached response body in a thread-safe manner
Closes gh-35745
2025-11-02 20:40:02 +01:00
Juergen Hoeller a33027703d Preserve Connection readOnly state for defaultReadOnly DataSource
Includes DataSourceTransactionManagerTests alignment with main branch.

Closes gh-35743
2025-11-02 17:28:12 +01:00
Sam Brannen ae804cb2d0 Improve @⁠NumberFormat Javadoc
See gh-35742
2025-11-02 16:23:47 +01:00
Stefano Cordio 46503d6a45 Fix typo in @⁠NumberFormat Javadoc
Closes gh-35742

Signed-off-by: Stefano Cordio <stefano.cordio@gmail.com>
2025-11-02 16:14:11 +01:00
Sam Brannen b4a13dddfc Fix JUnit Jupiter discovery issues on 6.2.x 2025-11-01 14:46:23 +01:00
Sam Brannen 661dca5e54 Remove accidental use of SpringExtension in ServletContextAwareBeanWacTests 2025-11-01 14:26:08 +01:00
Sam Brannen b976010a9e Simplify MockMvcClientHttpRequestFactoryTests 2025-11-01 14:26:07 +01:00
Juergen Hoeller 15563ee54e Polishing 2025-11-01 12:43:51 +01:00
Artur Signell 97586b525f fix: Fix PathMatchingResourcePatternResolver to handle absolute paths in JAR manifests
When JAR manifest Class-Path entries contain absolute paths (as Gradle
creates on Windows for long classpaths), PathMatchingResourcePatternResolver
incorrectly rejected them.

Fixes #35730

Signed-off-by: Artur Signell <artur@vaadin.com>
2025-11-01 12:25:20 +01:00
Sam Brannen f89737e398 Upgrade to JUnit 5.14.1
Closes gh-35739
2025-11-01 11:05:43 +01:00
Stéphane Nicoll ecdf069c5d Add AOT support for AutowiredPropertyMarker
Closes gh-35731
2025-10-31 15:30:54 +01:00
Anton Xu 01a58a253b Fix minor typo in RestClient
Closes gh-35723
Signed-off-by: Anton Xu <anton-xu@hotmail.com>
2025-10-30 19:41:56 +01:00
Juergen Hoeller f28e245baa Upgrade to Groovy 4.0.29, Jetty 12.0.29, Jackson 2.18.5 2025-10-30 17:30:21 +01:00
Park Juhyeong 14579b7848 Fix concurrency permit leak causing permanent deadlock in SimpleAsyncTaskExecutor
When concurrency limiting is enabled via setConcurrencyLimit() and
thread creation fails in doExecute() (e.g., OutOfMemoryError from
Thread.start()), the concurrency permit acquired by beforeAccess()
is never released because TaskTrackingRunnable.run() never executes.

This causes the concurrency count to permanently remain at the limit,
causing all subsequent task submissions to block forever in
ConcurrencyThrottleSupport.onLimitReached().

Root cause:
- beforeAccess() increments concurrencyCount
- doExecute() throws Error before thread starts
- TaskTrackingRunnable.run() never executes
- afterAccess() in finally block never called
- Concurrency permit permanently leaked

Solution:
Wrap doExecute() in try-catch block in the concurrency throttle path
and call afterAccess() in catch block to ensure permit is always
released, even when thread creation fails.

The fix only applies to the concurrency throttle path. The
activeThreads-only path does not need fixing because it never calls
beforeAccess(), so there is no permit to leak.

Test approach:
The test simulates thread creation failure and verifies that a
subsequent execution does not deadlock. The first execution should
fail with some exception (type doesn't matter), and the second
execution should complete within timeout if the permit was properly
released.

Signed-off-by: Park Juhyeong <wngud5957@naver.com>
2025-10-30 17:29:39 +01:00
Juergen Hoeller 5471961f06 Restore exposure of original BatchUpdateException as root cause
Closes gh-35717
See gh-35547
2025-10-30 14:59:00 +01:00
rstoyanchev 715bc68c16 Rename methods in FragmentsRendering
Previous commit 81ea35c726 in main for 7.0
should have been applied in 6.2.x first for 6.2.1.

This commit applies the changes in 6.2.x as intended,
effective as of 6.2.13.

Closes gh-33974
2025-10-30 12:17:51 +00:00
Sam Brannen 9c24f7ba8c Document test-method scoped TestContext semantics
Although gh-35680 introduced support for JUnit Jupiter's TEST_METHOD
ExtensionContextScope in the SpringExtension and
BeanOverrideTestExecutionListener, those were internal changes that are
not directly visible by TestExecutionListener authors.

However, in order to be compatible with a test-method scoped
TestContext (which takes its values from the current Jupiter
ExtensionContext), existing third-party TestExecutionListener
implementations may need to be modified similar to how
BeanOverrideTestExecutionListener was modified in commit d24a31d469.

To raise awareness of how to deal with such issues, this commit
documents test-method TestContext semantics for TestExecutionListener
authors.

Closes gh-35716
2025-10-30 11:22:25 +01:00
Juergen Hoeller a40647a62f Remove empty ConstraintValidator#initialize implementations 2025-10-28 20:38:08 +01:00
Juergen Hoeller b53fb13f30 Add tests for name-based dependency resolution against util:map
See gh-35690
2025-10-28 20:34:49 +01:00
Park Juhyeong 4b7b280ac3 Optimize resource URL resolution in SortedResourcesFactoryBean
Cache resource URLs before sorting to eliminate repeated I/O calls
during comparator operations. The previous implementation called
getURL() multiple times per resource during sorting (O(n log n)
calls), and silently swallowed IOExceptions by returning 0,
potentially causing unstable sort results.

This change:
- Caches URLs once per resource before sorting (O(n) I/O calls)
- Removes unnecessary ArrayList conversions
- Provides clear exception handling with context
- Improves performance by ~70% for typical use cases

Signed-off-by: Park Juhyeong <wngud5957@naver.com>
2025-10-28 20:30:33 +01:00
Sébastien Deleuze b3aefac9c3 Remove jibx-marshaller element from spring-oxm.xsd
Closes gh-35699
2025-10-28 15:38:53 +01:00
rstoyanchev b19059f6cb Handle null from JDK HttpResponse#body
Closes gh-35692
2025-10-28 11:44:16 +00:00
Sam Brannen b1f5b61bcd Abort search for static methods in getPubliclyAccessibleMethodIfPossible()
Prior to this commit, getPubliclyAccessibleMethodIfPossible() in
ClassUtils incorrectly returned a hidden static method as an
"equivalent" method for a static method with the same signature;
however, a static method cannot be overridden and therefore has no
"equivalent" method in a super type.

To fix that bug, this commit immediately aborts the search for an
"equivalent" publicly accessible method when the original method is a
static method.

See gh-33216
See gh-35189
See gh-35556
Closes gh-35667
2025-10-26 15:21:17 +01:00
rstoyanchev 810e069bcc FieldError uses HexFormat to format byte[]
See gh-35675
2025-10-24 13:01:28 +01:00
Elijah Mock 62f42cab6b Fix minor typo in JDBC Core Classes documentation
This commit adds a missing closing parenthesis in an example.

Closes gh-35684

Signed-off-by: Elijah Mock <28277163+ekcom@users.noreply.github.com>
2025-10-24 13:56:25 +02:00
Sam Brannen 9ee16b8ea3 Switch back to HSQL for JpaEntityListenerTests on main 2025-10-22 19:14:26 +02:00
Sam Brannen e61884e4bd Introduce tests for "No transaction in progress for @⁠Nested test class"
Since we now officially support the TEST_METHOD ExtensionContextScope
(see gh-35676 and gh-35680), this commit introduces tests which
demonstrate that the issue raised in gh-34576 is no longer an "issue" if
the user indirectly configures the SpringExtension to use the TEST_METHOD
scope via the "junit.jupiter.extensions.testinstantiation.extensioncontextscope.default"
configuration parameter.
2025-10-22 18:58:08 +02:00
Sam Brannen 0f2fc79fb7 Update exception message to use correct test class
See gh-35680
2025-10-22 18:04:13 +02:00
Sam Brannen ba70c1384a Polish SpringExtension internals 2025-10-22 17:07:53 +02:00
Sam Brannen d24a31d469 Support JUnit Jupiter ExtensionContextScope.TEST_METHOD
Historically, @⁠Autowired fields in an enclosing class of a @⁠Nested
test class have been injected from the ApplicationContext for the
enclosing class. If the enclosing test class and @⁠Nested test class
share the same ApplicationContext configuration, things work as
developers expect. However, if the enclosing class and @⁠Nested test
class have different ApplicationContexts, that can lead to
difficult-to-debug scenarios. For example, a bean injected into the
enclosing test class will not participate in a test-managed transaction
in the @⁠Nested test class (see gh-34576).

JUnit Jupiter 5.12 introduced a new ExtensionContextScope feature which
allows the SpringExtension to behave the same for @⁠Autowired fields as
it already does for @⁠Autowired arguments in lifecycle and test
methods. Specifically, if a developer sets the ExtensionContextScope to
TEST_METHOD — for example, by configuring the following configuration
parameter as a JVM system property or in a `junit-platform.properties`
file — the SpringExtension already supports dependency injection from
the current, @⁠Nested ApplicationContext in @⁠Autowired fields in an
enclosing class of the @⁠Nested test class.

junit.jupiter.extensions.testinstantiation.extensioncontextscope.default=test_method

However, there are two scenarios that fail as of Spring Framework
6.2.12.

1. @⁠TestConstructor configuration in @⁠Nested class hierarchies.
2. Field injection for bean overrides (such as @⁠MockitoBean) in
   @⁠Nested class hierarchies.

Commit 82c34f7b51 fixed the SpringExtension to support scenario #2
above.

To fix scenario #1, this commit revises
BeanOverrideTestExecutionListener's injectField() implementation to
look up the fields to inject for the "current test instance" instead of
for the "current test class".

This commit also introduces tests for both scenarios.

See gh-34576
See gh-35676
Closes gh-35680
2025-10-22 17:00:44 +02:00
Brian Clozel a5141b187a Fix '**' parsing within a PathPattern segment
Prior to this commit, a regexp path segment ending with a double wilcard
(like "/path**") would be incorrectly parsed as a double wildcard
segment ("/**").

This commit fixes the incorrect parsing.

See gh-35679
2025-10-22 12:21:57 +02:00
Brian Clozel d3c1e678c2 Support wildcard path elements at the start of path patterns
Prior to this commit, the `PathPattern` and `PathPatternParser` would
allow multiple-segments matching and capturing with the following:

* "/files/**" (matching 0-N segments until the end)
* "/files/{*path}" (matching 0-N segments until the end and capturing
  the value as the "path" variable)

This would be only allowed as the last path element in the pattern and
the parser would reject other combinations.

This commit expands the support and allows multiple segments matching at
the beginning of the path:

* "/**/index.html" (matching 0-N segments from the start)
* "/{*path}/index.html" (matching 0-N segments until the end and capturing
  the value as the "path" variable)

This does come with additional restrictions:

1. "/files/**/file.txt" and "/files/{*path}/file.txt" are invalid,
   as multiple segment matching is not allowed in the middle of the
   pattern.
2. "/{*path}/files/**" is not allowed, as a single "{*path}" or "/**"
   element is allowed in a pattern
3. "/{*path}/{folder}/file.txt"  "/**/{folder:[a-z]+}/file.txt" are
   invalid because only a literal pattern is allowed right after
   multiple segments path elements.

Closes gh-35679
2025-10-22 12:21:57 +02:00
Sam Brannen 82c34f7b51 Introduce isAutowirableConstructor(Executable,PropertyProvider) in TestConstructorUtils
This commit introduces a new isAutowirableConstructor(Executable, PropertyProvider)
overload in TestConstructorUtils and deprecates all other existing variants
for removal in 7.1.

Closes gh-35676
2025-10-21 17:37:04 +02:00
Sam Brannen cb0f26a152 Use consistent naming for Bean Override test classes
cherry-picked from c6e5cfe03d
2025-10-21 16:25:12 +02:00
Sam Brannen bccfbfd630 Fix previous commit for 6.2.x compatibility
See gh-35674
2025-10-21 15:37:35 +02:00
Brian Clozel 506b76032f Add missing reflection hints for JdbcUtils
This commit adds the missing reflection hints for `JdbcUtils`, as this
class reflects on `java.sql.Types` public fields.

Fixes gh-35674
2025-10-21 13:50:13 +02:00
Juergen Hoeller 7adcd99ea2 Polishing 2025-10-21 00:59:56 +02:00
Juergen Hoeller 765e30c3a6 Polishing 2025-10-18 15:30:15 +02:00
HJC96 d7fc07e73c Fix typos
Closes gh-35656
Signed-off-by: HJC96 <gkswlcjs2@naver.com>
2025-10-17 15:46:27 +02:00
Brian Clozel 18a879779e Next development version (v6.2.13-SNAPSHOT) 2025-10-16 09:32:20 +02:00
Juergen Hoeller c53132ecdf Polishing 2025-10-15 19:40:09 +02:00
rstoyanchev 03c3ec1577 Fall back on remoteHost if remoteAddress is null
See gh-35589
2025-10-15 16:42:40 +01:00
rstoyanchev c88bfc54c9 Refactor state management in StompSubProtocolHandler
Closes gh-35591
2025-10-15 12:31:42 +01:00
Sam Brannen a96558c965 Revise commit 01acb80501
See gh-35631
2025-10-15 12:48:52 +02:00
Sam Brannen 1612b7c5db Remove test prefixes 2025-10-15 11:28:49 +02:00
Sam Brannen 01acb80501 Improve exception handling in ConfigurationClassBeanDefinitionReader
Thanks to a proposal from @wilkinsona, this commit introduces a
try-catch block in loadBeanDefinitions(...) which throws an
IllegalStateException that provides context regarding the configuration
class and cause of the failure.

Closes gh-35631

Co-authored-by: Andy Wilkinson <andy.wilkinson@broadcom.com>
2025-10-15 11:26:06 +02:00
Juergen Hoeller f4438ce9e3 Upgrade to Reactor 2024.0.11 and Micrometer 1.14.12
Includes Netty 4.1.128

Closes gh-35638
Closes gh-35640
2025-10-14 19:21:34 +02:00
Juergen Hoeller 5033b9d3c5 Reset by-type cache for Object after registering a new singleton
Closes gh-35634
2025-10-14 19:20:57 +02:00
Juergen Hoeller d733023a29 Consistently apply fallback attribute to proxy definition as well
See gh-35627
2025-10-14 19:17:57 +02:00
Schäfer, H.H. (Hans Hosea) df67c1cf2d 35626: defaultCandidate for scoped proxies
Signed-off-by: Schäfer, H.H. (Hans Hosea) <HansHosea.Schaefer@ing.de>
2025-10-14 19:07:03 +02:00
rstoyanchev 05814f7a42 Polishing contribution
Closes gh-35625
2025-10-14 16:49:10 +01:00
Marius Lichtblau ba2bb08589 Release DataBuffer in AbstractCharSequenceDecoder
if String creation fails

See gh-35625

Signed-off-by: Marius Lichtblau <marius@lichtblau.io>
2025-10-14 16:49:10 +01:00
Edgar Asatryan 141df5291d Prevent NoClassDefFoundError when Jetty Reactive HttpClient not on classpath
Closes gh-35608

Signed-off-by: Edgar Asatryan <nstdio@gmail.com>
2025-10-14 16:49:10 +01:00
Sébastien Deleuze dcfe33f427 Fix Hibernate Javadoc to avoid a redirect 2025-10-14 17:40:44 +02:00
Juergen Hoeller 3a61460f91 Use JarFile#entries() instead of #stream() for consistent entry paths
Closes gh-35617
2025-10-14 11:23:34 +02:00
Brian Clozel ee284f2ee6 Add "forEachByte" variant to DataBuffer
As reported in gh-34651, `DataBuffer#getByte` can be inefficient for
some implementations, as bound checks are performed for each call.

This commit introduces a new `forEachByte` method that helps with
traversing operations without paying the bound check cost for each byte.

Closes gh-35623
2025-10-13 18:28:34 +02:00
Sam Brannen 2591cab561 Polishing 2025-10-13 15:12:21 +02:00
Sam Brannen 8456cd1e74 Polish contribution
See gh-35587
2025-10-13 15:12:21 +02:00
Igor Murzich 7699b4af9c Retain order of produces media types in @⁠ExceptionHandler
Closes gh-35587

Signed-off-by: Igor Murzich <imurzich@gmail.com>
2025-10-13 15:12:21 +02:00
Juergen Hoeller 6c5de48059 Ignore SQL state 3B001 in HSQLDB exception message as well
Closes gh-35618
See gh-35564
2025-10-13 15:10:20 +02:00
Juergen Hoeller 9f678ce698 Upgrade to Jetty 12.0.28, Undertow 2.3.20, RxJava 3.1.12, Aalto 1.3.4, Gson 2.13.2, Selenium 4.36, HtmlUnit 4.17, Mockito 5.20, AssertJ 3.27.6 2025-10-11 15:12:21 +02:00
Juergen Hoeller 467a484df6 Polishing
See gh-35460
2025-10-11 15:11:16 +02:00
Juergen Hoeller 83efe8cff4 Remove deprecation on CandidateComponentsIndex(Loader)
See gh-35472
2025-10-11 15:10:42 +02:00
rstoyanchev 2c83144946 Use getRemoteAddr in ServletServerHttpRequest
Closes gh-35589
2025-10-10 17:24:48 +01:00
rstoyanchev c165dd5e0e Update Javadoc of reactive WebSocketHandler
Replace suggestion to use zip with and operator.

Closes gh-35572
2025-10-10 17:23:03 +01:00
Juergen Hoeller 449b85f446 Avoid overhead for parsing plain values and simple placeholders
Closes gh-35594
2025-10-10 17:03:34 +02:00
Juergen Hoeller c2a66e723f Polishing 2025-10-09 20:34:03 +02:00
Juergen Hoeller 2ee34a5632 Add MySQLTableMetaDataProvider for correct generated-keys support
Closes gh-35593
2025-10-09 20:30:25 +02:00
Juergen Hoeller 1bc82d241a Remove deprecation on CandidateComponentsIndex(Loader)
Closes gh-35472
2025-10-09 20:26:59 +02:00
Juergen Hoeller 80e7ee321e Mark bootstrap thread for entire finishBeanFactoryInitialization phase
Closes gh-35398
2025-10-06 14:08:03 +02:00
Juergen Hoeller ecd3dd8883 Consistent local synchronization in getObjectFromFactoryBean
Closes gh-35545
2025-10-03 17:29:14 +02:00
Juergen Hoeller 332953c9a4 Align BatchUpdateException handling among SQLExceptionTranslator variants
Closes gh-35547
2025-10-03 14:51:15 +02:00
Sam Brannen 1cdd56bf02 Log multiple primary bean detection in DefaultListableBeanFactory
Prior to this commit, a NoUniqueBeanDefinitionException was thrown when
multiple primary beans were detected within a given set of beans, but
nothing was logged. For use cases where the exception is handled by
infrastructure code, it may not be obvious to the developer what the
problem is.

To address that, a TRACE message is now logged whenever multiple
competing primary beans are detected in DefaultListableBeanFactory.

Closes gh-35550
2025-10-03 14:09:52 +02:00
Juergen Hoeller 3041071269 Consistently apply useCaches for single Resource lookup
Closes gh-35465
2025-10-02 21:53:47 +02:00
Juergen Hoeller 2da821389c Remove redundant object allocation in cglib proxy method calls
Reformatted with Spring patch markers and backported to 6.2.12

Closes gh-35543
2025-10-02 21:53:34 +02:00
Juergen Hoeller d484e4f3ff Ignore SQL state 3B001 in releaseSavepoint (for HSQLDB)
Closes gh-35564
2025-10-02 13:01:30 +02:00
Juergen Hoeller 74dc61b8c4 Fall back to local synchronization in getObjectFromFactoryBean
Closes gh-35545
2025-10-02 13:01:03 +02:00
Sam Brannen 717358b56b Short circuit ClassUtils.findPubliclyAccessibleMethodIfPossible(...)
Once we find a publicly accessible method, there is no need to continue
traversing the type hierarchy.

See gh-35556
2025-10-02 11:44:54 +02:00
Sébastien Deleuze 836634c47f Upgrade CI workflow from Java 24 to Java 25 2025-10-02 10:19:42 +02:00
Juergen Hoeller a6f6ecfe6c Revise getPubliclyAccessibleMethodIfPossible to rely on Module#isExported
This avoids reflection and cache access for regular public and exported types.

Closes gh-35556
2025-10-01 19:56:23 +02:00
Juergen Hoeller e3da26ebbd Clarify event parameter type for multiple mapped classes
Closes gh-35506
2025-10-01 19:55:42 +02:00
Maziyar Bahramian e1c008f5a3 Fix URI Patterns docs for WebMVC and WebFlux
Closes gh-35551
Signed-off-by: Maziyar Bahramian <maziyar.bahramian@gmail.com>
2025-10-01 19:39:57 +02:00
Sébastien Deleuze cb849a7071 Add a test for CGLIB Enhancer Kotlin refinements
This commit adds a reproducer for the change of behavior introduced via
https://youtrack.jetbrains.com/issue/KT-76667. The test is only broken
with Kotlin 2.2.20+ without the related fix (see previous commit).

Closes gh-35487
2025-10-01 19:21:40 +02:00
Juergen Hoeller 3e37279db6 Make CGLIB Enhancer compatible with Kotlin 2.2.20+
This commit refines Enhancer#emitMethods to support the changes
introduced by https://youtrack.jetbrains.com/issue/KT-76667.

See gh-35487
2025-10-01 19:14:14 +02:00
rstoyanchev b3264ec2a8 Fix typo 2025-10-01 16:13:40 +01:00
rstoyanchev df860fd3cd Polishing contribution
Closes gh-35493
2025-10-01 14:45:18 +01:00
Réda Housni Alaoui 636523a2f5 AbstractMockHttpServletRequestBuilder#buildRequest is not idempotent
See gh-35493

Signed-off-by: Réda Housni Alaoui <reda-alaoui@hey.com>
2025-10-01 14:44:23 +01:00
rstoyanchev a19b51b7e0 Handle invalid position in ResourceHttpMessageWriter
Closes gh-35536
2025-10-01 14:44:05 +01:00
rstoyanchev fbdece6759 Polishing in ResourceHttpMessageWriter
See gh-35536
2025-10-01 14:42:01 +01:00
Sam Brannen 64d42fefda Fix idref example in reference manual
Closes gh-35560
2025-10-01 13:19:54 +02:00
Sam Brannen 447cfa18e9 Polishing 2025-10-01 13:19:25 +02:00
Sam Brannen ec3d9d6253 Upgrade to JUnit 5.14
Closes gh-35555
2025-09-30 12:43:53 +02:00
Sam Brannen 5cd2cb38e1 Make AbstractTestNGSpringContextTests thread-safe regarding tracked exceptions
Prior to this commit, AbstractTestNGSpringContextTests was not
thread-safe with regard to tracked exceptions.

To address that, AbstractTestNGSpringContextTests now tracks the test
exception via a ThreadLocal.

Closes gh-35528
2025-09-25 17:51:39 +02:00
rstoyanchev e9fb5eb38a Respect forwarded path in UrlHandlerFilter
Closes gh-35509
2025-09-25 12:19:56 +01:00
rstoyanchev 5a858915ea Revise parsed path handling in UrlHandlerFilter
Closes gh-35538
2025-09-24 19:08:55 +01:00
Brian Clozel d85a020e4e Improve Task Javadoc about Runnable wrapping
Closes gh-35394
2025-09-19 18:05:02 +02:00
Brian Clozel 0cc79ba366 Catch EOFException in IntrospectingClientHttpResponse
Prior to this commit, the `IntrospectingClientHttpResponse` would try
and read the HTTP response stream in order to check for the presence of
a non-empty message body.

Developers reported that in some cases, an `EOFException` is thrown
instead of returning -1 from the `read()` method. This commit ensures
that this case is taken into account and that we report the response as
an empty body in these cases.

Closes gh-35361
2025-09-19 17:49:12 +02:00
Sam Brannen 1e29911292 Upgrade to AssertJ 3.27.5 2025-09-19 11:23:08 +02:00
Juergen Hoeller 931686a5ee Upgrade to SnakeYAML 2.5, Protobuf 4.32.1, ActiveMQ 5.17.7 and Artemis 2.42, EasyMock 5.6, AssertJ 3.27.4, XMLUnit 2.10.4, Dom4J 2.2 2025-09-17 18:18:35 +02:00
Juergen Hoeller bf715ac23e Polishing 2025-09-17 18:10:19 +02:00
Brian Clozel b213344d25 Fix synchronization in ResponseBodyEmitter
See gh-35423
Fixes gh-35466

(cherry picked from commit 20e1149dde)
2025-09-17 18:07:45 +02:00
Stéphane Nicoll 0a48984fab Suppress deprecating warnings for getInstanceSupplier() method as well
This commit fixes code generation for a bean produced by a protected
factory method. Previously only the code generated for public methods,
i.e. without a dedicated instance supplier method, was handled.

Closes gh-35486
2025-09-16 16:08:15 +02:00
Brian Clozel cbdd107799 Next development version (v6.2.12-SNAPSHOT) 2025-09-11 09:40:23 +02:00
Juergen Hoeller d17601e01c Upgrade to Undertow 2.3.19, RxJava 3.1.11, Aalto 1.3.3 2025-09-10 18:38:20 +02:00
Juergen Hoeller 5b387615c6 Clarify intended nestedTransactionAllowed default in JpaTransactionManager
Closes gh-35212
2025-09-10 18:06:44 +02:00
Sam Brannen 0e3e34bee0 Find annotations on parameters in overridden non-public methods
Prior to this commit, annotations were not found on parameters in an
overridden method unless the method was public. Specifically, the
search algorithm in AnnotatedMethod did not consider a protected or
package-private method in a superclass to be a potential override
candidate. This affects parameter annotation searches in
spring-messaging, spring-webmvc, spring-webflux, and any other
components that use or extend AnnotatedMethod.

To address that, this commit revises the search algorithm in
AnnotatedMethod to consider all non-final declared methods as potential
override candidates, thereby aligning with the search logic in
AnnotationsScanner for the MergedAnnotations API.

Closes gh-35349
2025-09-10 14:24:24 +02:00
Sam Brannen 4745c7cf3c Name local variables consistently 2025-09-10 14:08:20 +02:00
Juergen Hoeller 275fb52ad6 Upgrade to Reactor 2024.0.10 and Micrometer 1.14.11
Closes gh-35454
Closes gh-35455
2025-09-09 18:45:38 +02:00
Juergen Hoeller 7f9aa39748 Polishing 2025-09-09 18:45:04 +02:00
Taeik Lim c788554b1d Avoid thread pinning in SseEmitter, ResponseBodyEmitter
Closes gh-35423

Signed-off-by: Taeik Lim <sibera21@gmail.com>
2025-09-09 16:38:10 +02:00
Sébastien Deleuze 9e8c64011d Make JsonPathAssertions#isEqualTo parameter nullable
Closes gh-35445
2025-09-09 11:25:58 +02:00
Juergen Hoeller ebb8e34570 Upgrade to Jetty 12.0.26, Jetty Reactive HttpClient 4.0.11, Netty 4.1.127, HtmlUnit 4.16 2025-09-08 18:11:27 +02:00
Juergen Hoeller 9ba954c330 Fix FileSystemUtils for Windows/Linux path difference
See gh-35443
2025-09-08 17:51:58 +02:00
Juergen Hoeller ba52164373 Provide graceful fallback for non-default NIO file systems
Closes gh-35443
2025-09-08 17:28:45 +02:00
rstoyanchev 977582fced Document data binding for functional endpoints
Closes gh-35367
2025-09-08 10:12:20 +01:00
Sam Brannen 64721b3bc0 Polish formatting 2025-09-03 16:24:56 +02:00
Sam Brannen 02f0f92a72 Polish contribution
See gh-35400
2025-09-03 16:22:55 +02:00
Lukáš Kvídera db9e938ec4 Detect Informix error codes as DuplicateKeyException
Closes gh-35400

Signed-off-by: Lukáš Kvídera <kvideral@qwsome.eu>
2025-09-03 16:20:19 +02:00
Juergen Hoeller 3a4315bf16 Keep mainThreadPrefix exposed until background init threads finished
Closes gh-35409
2025-09-03 15:45:12 +02:00
Sam Brannen 33fe8d29c1 Document potential need to use Mockito.doXxx() to stub a @⁠MockitoSpyBean
Closes gh-35410
2025-09-03 14:52:58 +02:00
Sam Brannen b741632e99 Polish wording in web sections 2025-08-29 17:25:15 +02:00
Tran Ngoc Nhan cd208797e2 Fix links to Reactive Libraries and RestTemplate
Closes gh-35392

Signed-off-by: Tran Ngoc Nhan <ngocnhan.tran1996@gmail.com>
2025-08-29 17:23:13 +02:00
Brian Clozel 764336f0f2 Fix Jetty DataBufferFactory memory leak
Prior to this commit, gh-32097 added native support for Jetty for both
client and server integrations. The `JettyDataBufferFactory` was
promoted as a first class citizen, extracted from a private class in the
client support. To accomodate with server-side requirements, an extra
`buffer.retain()` call was performed.
While this is useful for server-side support, this introduced a bug in
the data buffer factory, as wrapping an existing chunk means that this
chunk is already retained.

This commit fixes the buffer factory implementation and moved existing
tests from mocks to actual pooled buffer implementations from Jetty.
The extra `buffer.retain()` is now done from the server support, right
before wrapping the buffer.

Fixes gh-35319
2025-08-27 13:36:34 +02:00
Sam Brannen 4903fee939 Permit @⁠Nullable value in ResponseCookie from*() factory methods
Closes gh-35377
2025-08-26 11:01:29 +02:00
Sam Brannen 6978f0a398 Document terms and units in DataSize.parse(...) methods
Closes gh-35298
2025-08-24 14:02:04 +02:00
Juergen Hoeller f62519bb55 Add cancelRemainingTasksOnClose flag for enforcing early interruption
Closes gh-35372
2025-08-24 10:31:01 +02:00
Juergen Hoeller 0e2af5d113 Avoid default AutoCloseable implementation in ExecutorService on JDK 19+
Consistently calls shutdown() unless a specific close() method has been provided in a subclass.

Closes gh-35316
2025-08-24 10:30:48 +02:00
Daniel Garnier-Moiroux ed7c3d737c Fix broken link in WebDriver docs
Closes gh-35374

Signed-off-by: Daniel Garnier-Moiroux <git@garnier.wf>
2025-08-23 13:41:40 +02:00
Juergen Hoeller 01b24f2644 Upgrade to Protobuf 4.32, HtmlUnit 4.15, Mockito 5.19 2025-08-22 23:05:13 +02:00
Juergen Hoeller 4a4cf8a787 Remove erroneous javadoc symbol 2025-08-22 22:38:34 +02:00
Juergen Hoeller 55181fa1c9 Polishing 2025-08-22 22:00:52 +02:00
Juergen Hoeller 300ae841ce Align setBeanResolver nullability with getBeanResolver
Includes consistent javadoc for all applicable methods.

Closes gh-35371
2025-08-22 22:00:22 +02:00
Juergen Hoeller c248f94e5a Cache bean type next to primary bean names (on singleton creation)
This avoids singleton access for type checks in hasPrimaryConflict.

Closes gh-35330
2025-08-22 21:59:38 +02:00
Sam Brannen 19d5ec6781 Improve documentation for ApplicationEvents to clarify recommended usage
See gh-35335
2025-08-20 16:42:22 +02:00
khj68 c0b71f8999 Improve Javadoc of ApplicationEvents to clarify preferred usage
This commit reorders and clarifies the usage instructions for
ApplicationEvents to:

1. Recommend method parameter injection as the primary approach, since
   ApplicationEvents has a per-method lifecycle
2. Clarify that ApplicationEvents is not a general Spring bean and
   cannot be constructor-injected
3. Explicitly state that field injection is an alternative approach

This addresses confusion where developers expect ApplicationEvents to
behave like a regular Spring bean eligible for constructor injection.

See gh-35297
Closes gh-35335

Signed-off-by: khj68 <junthewise@gmail.com>
2025-08-20 16:31:41 +02:00
Sam Brannen 5d214c2624 Polishing 2025-08-20 16:31:41 +02:00
Sam Brannen 6d710d482a Find annotation on overridden method in type hierarchy with unresolved generics
Prior to this commit, the MergedAnnotations support (specifically
AnnotationsScanner) and AnnotatedMethod did not find annotations on
overridden methods in type hierarchies with unresolved generics.

The reason for this is that ResolvableType.resolve() returns null for
such an unresolved type, which prevents the search algorithms from
considering such methods as override candidates.

For example, given the following type hierarchy, the compiler does not
generate a method corresponding to processOneAndTwo(Long, String) for
GenericInterfaceImpl. Nonetheless, one would expect an invocation of
processOneAndTwo(Long, String) to be @⁠Transactional since it is
effectively an invocation of processOneAndTwo(Long, C) in
GenericAbstractSuperclass, which overrides/implements
processOneAndTwo(A, B) in GenericInterface, which is annotated with
@⁠Transactional.

However, the MergedAnnotations infrastructure currently does not
determine that processOneAndTwo(Long, C) is @⁠Transactional since it is
not able to determine that processOneAndTwo(Long, C) overrides
processOneAndTwo(A, B) because of the unresolved generic C.

interface GenericInterface<A, B> {

    @⁠Transactional
    void processOneAndTwo(A value1, B value2);
}

abstract class GenericAbstractSuperclass<C> implements GenericInterface<Long, C> {

    @⁠Override
    public void processOneAndTwo(Long value1, C value2) {
    }
}

static GenericInterfaceImpl extends GenericAbstractSuperclass<String> {
}

To address such issues, this commit changes the logic in
AnnotationsScanner.hasSameGenericTypeParameters() and
AnnotatedMethod.isOverrideFor() so that they use
ResolvableType.toClass() instead of ResolvableType.resolve(). The
former returns Object.class for an unresolved generic which in turn
allows the search algorithms to properly detect method overrides in
such type hierarchies.

Closes gh-35342
2025-08-19 12:28:12 +02:00
Stefano Cordio ed28390d24 Refine @Contract Javadoc
This commit removes references to the `pure` attribute.
Relates to gh-33820.

Closes gh-35285
Signed-off-by: Stefano Cordio <stefano.cordio@gmail.com>
2025-08-14 16:12:46 +02:00
Stéphane Nicoll e2085063f6 Next development version (v6.2.11-SNAPSHOT) 2025-08-14 09:55:02 +02:00
Stéphane Nicoll edda4731e1 Build against Java 24
Closes gh-35326
2025-08-14 09:06:18 +02:00
Stéphane Nicoll 9fa2d7d190 Upgrade to Jackson 2.18.4.1
Closes gh-35322
2025-08-14 08:38:58 +02:00
Stéphane Nicoll c30427fd4e Upgrade to Netty 4.1.124.Final
Closes gh-35321
2025-08-14 08:38:34 +02:00
Juergen Hoeller 1d908f1847 Upgrade to Reactor 2024.0.9 and Micrometer 1.14.10
Includes Groovy 4.0.28, JRuby 9.4.13, Jetty 12.0.25, Caffeine 3.2.2, Protobuf 4.31.1, Selenium 4.35, HtmlUnit 4.14

Closes gh-35312
Closes gh-35313
2025-08-13 00:04:31 +02:00
Sam Brannen 37b076be51 Support multiple result sets in ScriptUtils.executeSqlScript()
Prior to this commit, ScriptUtils.executeSqlScript() treated every
statement within the script as if it were a single insert/update/delete
statement. This disregarded the fact that the execution of a JDBC
Statement can result in multiple individual statements, some of which
result in a ResultSet and others that result in an update count.

For example, when executing a stored procedure on Sybase, ScriptUtils
did not execute all statements within the stored procedure.

To address that, this commit revises the implementation of
ScriptUtils.executeSqlScript() so that it handles multiple results and
differentiates between result sets and update counts.

Closes gh-35248
2025-08-11 17:44:39 +03:00
Juergen Hoeller a9453a5959 Polishing 2025-08-11 14:32:45 +02:00
Juergen Hoeller 3781ba223e Optimize NIO path resolution in PathEditor
Closes gh-35304
2025-08-11 14:32:39 +02:00
Sam Brannen f11a1e6f82 Polish tests 2025-08-11 11:27:10 +03:00
rstoyanchev ffc785471b Fix checkstyle error 2025-08-08 12:31:13 +01:00
rstoyanchev 6e2fbfe108 Polishing contribution
Closes gh-35232
2025-08-08 11:50:07 +01:00
秦利斌 968e037503 Add documentation of RequestMapping about SpEL
Signed-off-by: 秦利斌 <68638598+Allan-QLB@users.noreply.github.com>
2025-08-08 11:37:25 +01:00
rstoyanchev f0a9f649c1 Allow null in ProblemDetail#type
See gh-35294
2025-08-08 11:36:53 +01:00
rstoyanchev 600d6c6fc0 Update contribution
Closes gh-34721
2025-08-08 11:31:21 +01:00
giampaolo 7a55ce48a9 Handle CancellationException in JdkClientHttpRequest
Handle CancellationException in order to throw an HttpTimeoutException
when the timeout handler caused the cancellation.

See gh-34721

Signed-off-by: giampaolo <giampaorr@gmail.com>

fix: use timeoutHandler with a flag isTimeout

    Closes gh-33973

    Signed-off-by: giampaolo <giampaorr@gmail.com>
2025-08-08 11:31:21 +01:00
Juergen Hoeller 5df9fd4eff Polishing (aligned with main) 2025-08-06 19:01:18 +02:00
Juergen Hoeller da13a24604 Allow any @Transactional propagation for listener with BEFORE_COMMIT phase
Closes gh-35150
2025-08-01 21:15:56 +02:00
Juergen Hoeller 67e88f3c20 Align task execution tracking and thread interruption on shutdown
Closes gh-35254
2025-08-01 21:15:25 +02:00
Patrick Strawderman 24e66b63d1 Refine StringUtils#uriDecode and update documentation
Refine the StringUtils#uriDecode method in the following ways:
- Use a StringBuilder instead of ByteArrayOutputStream, and only decode
  %-encoded sequences.
- Use HexFormat.fromHexDigits to decode hex sequences.
- Decode to a byte array that is only allocated if encoded sequences are
  encountered.

This commit adds another optimization mainly for the use case where
there is no encoded sequence, and updates the Javadoc of both
StringUtils#uriDecode and UriUtils#decode to match the implementation.

Signed-off-by: Patrick Strawderman <pstrawderman@netflix.com>
Co-Authored-by: Sebastien Deleuze <sebastien.deleuze@broadcom.com>

Closes gh-35253
2025-07-29 21:44:26 +02:00
Juergen Hoeller f3832c7262 Add note on SQL types with SqlBinaryValue/SqlCharacterValue
Closes gh-34786
2025-07-28 22:06:38 +02:00
Juergen Hoeller 16e99f289c Accept support for generated keys column name array on HSQLDB/Derby
Closes gh-34790
2025-07-28 22:04:18 +02:00
Juergen Hoeller 642e554c52 Process PostgreSQL-returned catalog/schema names in given case
Closes gh-35064
2025-07-28 20:28:45 +02:00
Juergen Hoeller 4f6304707d Polishing 2025-07-25 22:40:15 +02:00
Juergen Hoeller 3c112703d9 Introduce useCaches flag on UrlResource (for URLConnection access)
Propagated from PathMatchingResourcePatternResolver's setUseCaches.

Closes gh-35218
2025-07-25 22:40:09 +02:00
Juergen Hoeller 8c44a61033 Invalidate cache entries for matching types after singleton creation
Closes gh-35239
2025-07-25 22:38:57 +02:00
Sébastien Deleuze 5e338ef1b8 Make MessageSource locale parameter nullable
Closes gh-35230
2025-07-23 16:02:38 +02:00
Sam Brannen 445da24631 Upgrade to JUnit 5.13.4
Closes gh-35229
2025-07-21 13:17:38 +03:00
Brian Clozel 6d97791f5e Next development version (v6.2.10-SNAPSHOT) 2025-07-17 09:55:21 +02:00
420 changed files with 10768 additions and 5085 deletions
+1 -1
View File
@@ -21,7 +21,7 @@ jobs:
toolchain: false
- version: 21
toolchain: true
- version: 23
- version: 25
toolchain: true
exclude:
- os:
+1 -1
View File
@@ -27,7 +27,7 @@ See the [Build from Source](https://github.com/spring-projects/spring-framework/
## Continuous Integration Builds
Information regarding CI builds can be found in the [Spring Framework Concourse pipeline](ci/README.adoc) documentation.
CI builds are defined with [GitHub Actions workflows](.github/workflows).
## Stay in Touch
+2 -2
View File
@@ -86,7 +86,7 @@ configure([rootProject] + javaProjects) { project ->
ext.javadocLinks = [
"https://docs.oracle.com/en/java/javase/17/docs/api/",
"https://jakarta.ee/specifications/platform/9/apidocs/",
"https://docs.jboss.org/hibernate/orm/5.6/javadocs/",
"https://docs.hibernate.org/orm/5.6/javadocs/",
"https://www.quartz-scheduler.org/api/2.3.0/",
"https://fasterxml.github.io/jackson-core/javadoc/2.14/",
"https://fasterxml.github.io/jackson-databind/javadoc/2.14/",
@@ -97,7 +97,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.13.3/api/",
// "https://junit.org/junit5/docs/5.14.1/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/",
+4 -2
View File
@@ -13,7 +13,9 @@ content:
- url: https://github.com/spring-projects/spring-framework
# Refname matching:
# https://docs.antora.org/antora/latest/playbook/content-refname-matching/
branches: ['main', '{6..9}.+({1..9}).x']
# branches: We include snapshots for main, 6.2.x, and 7.0.x to 9.*.x.
branches: ['main', '6.2.x', '{7..9}.+({0..9}).x']
# tags: We effectively include all releases from 6.0.9 to 9.*.*.
tags: ['v{6..9}.+({0..9}).+({0..9})?(-{RC,M}*)', '!(v6.0.{0..8})', '!(v6.0.0-{RC,M}{0..9})']
start_path: framework-docs
asciidoc:
@@ -36,4 +38,4 @@ runtime:
failure_level: warn
ui:
bundle:
url: https://github.com/spring-io/antora-ui-spring/releases/download/v0.4.18/ui-bundle.zip
url: https://github.com/spring-io/antora-ui-spring/releases/download/v0.4.25/ui-bundle.zip
@@ -1,24 +1,26 @@
[[beans-classpath-scanning]]
= Classpath Scanning and Managed Components
Most examples in this chapter use XML to specify the configuration metadata that produces
each `BeanDefinition` within the Spring container. The previous section
(xref:core/beans/annotation-config.adoc[Annotation-based Container Configuration]) demonstrates how to provide a lot of the configuration
metadata through source-level annotations. Even in those examples, however, the "base"
bean definitions are explicitly defined in the XML file, while the annotations drive only
the dependency injection. This section describes an option for implicitly detecting the
candidate components by scanning the classpath. Candidate components are classes that
match against a filter criteria and have a corresponding bean definition registered with
the container. This removes the need to use XML to perform bean registration. Instead, you
can use annotations (for example, `@Component`), AspectJ type expressions, or your own
Most examples in this chapter use XML to specify the configuration metadata that
produces each `BeanDefinition` within the Spring container. The previous section
(xref:core/beans/annotation-config.adoc[Annotation-based Container Configuration])
demonstrates how to provide a lot of the configuration metadata through source-level
annotations. Even in those examples, however, the "base" bean definitions are explicitly
defined in the XML file, while the annotations drive only the dependency injection.
This section describes an option for implicitly detecting the candidate components by
scanning the classpath. Candidate components are classes that match against a filter
criteria and have a corresponding bean definition registered with the container.
This removes the need to use XML to perform bean registration. Instead, you can use
annotations (for example, `@Component`), AspectJ type expressions, or your own
custom filter criteria to select which classes have bean definitions registered with
the container.
[NOTE]
====
You can define beans using Java rather than using XML files. Take a look at the
`@Configuration`, `@Bean`, `@Import`, and `@DependsOn` annotations for examples of how to
use these features.
`@Configuration`, `@Bean`, `@Import`, and `@DependsOn` annotations for examples
of how to use these features.
====
@@ -830,10 +832,10 @@ definitions, there is no notion of bean definition inheritance, and inheritance
hierarchies at the class level are irrelevant for metadata purposes.
For details on web-specific scopes such as "`request`" or "`session`" in a Spring context,
see xref:core/beans/factory-scopes.adoc#beans-factory-scopes-other[Request, Session, Application, and WebSocket Scopes]. As with the pre-built annotations for those scopes,
you may also compose your own scoping annotations by using Spring's meta-annotation
approach: for example, a custom annotation meta-annotated with `@Scope("prototype")`,
possibly also declaring a custom scoped-proxy mode.
see xref:core/beans/factory-scopes.adoc#beans-factory-scopes-other[Request, Session, Application, and WebSocket Scopes].
As with the pre-built annotations for those scopes, you may also compose your own scoping
annotations by using Spring's meta-annotation approach: for example, a custom annotation
meta-annotated with `@Scope("prototype")`, possibly also declaring a custom scoped-proxy mode.
NOTE: To provide a custom strategy for scope resolution rather than relying on the
annotation-based approach, you can implement the
@@ -875,7 +877,8 @@ Kotlin::
----
When using certain non-singleton scopes, it may be necessary to generate proxies for the
scoped objects. The reasoning is described in xref:core/beans/factory-scopes.adoc#beans-factory-scopes-other-injection[Scoped Beans as Dependencies].
scoped objects. The reasoning is described in
xref:core/beans/factory-scopes.adoc#beans-factory-scopes-other-injection[Scoped Beans as Dependencies].
For this purpose, a scoped-proxy attribute is available on the component-scan
element. The three possible values are: `no`, `interfaces`, and `targetClass`. For example,
the following configuration results in standard JDK dynamic proxies:
@@ -50,9 +50,8 @@ XML configuration:
The preceding XML is more succinct. However, typos are discovered at runtime rather than
design time, unless you use an IDE (such as https://www.jetbrains.com/idea/[IntelliJ
IDEA] or the {spring-site-tools}[Spring Tools for Eclipse])
that supports automatic property completion when you create bean definitions. Such IDE
assistance is highly recommended.
IDEA] or the {spring-site-tools}[Spring Tools]) that supports automatic property
completion when you create bean definitions. Such IDE assistance is highly recommended.
You can also configure a `java.util.Properties` instance, as follows:
@@ -85,11 +84,11 @@ element. The following example shows how to use it:
[source,xml,indent=0,subs="verbatim,quotes"]
----
<bean id="theTargetBean" class="..."/>
<bean id="collaborator" class="..." />
<bean id="theClientBean" class="...">
<bean id="client" class="...">
<property name="targetName">
<idref bean="theTargetBean"/>
<idref bean="collaborator" />
</property>
</bean>
----
@@ -99,28 +98,24 @@ following snippet:
[source,xml,indent=0,subs="verbatim,quotes"]
----
<bean id="theTargetBean" class="..." />
<bean id="collaborator" class="..." />
<bean id="theClientBean" class="...">
<property name="targetName" ref="theTargetBean"/>
<bean id="client" class="...">
<property name="targetName" value="collaborator" />
</bean>
----
The first form is preferable to the second, because using the `idref` tag lets the
container validate at deployment time that the referenced, named bean actually
exists. In the second variation, no validation is performed on the value that is passed
to the `targetName` property of the `client` bean. Typos are only discovered (with most
container validate at deployment time that the referenced, named bean actually exists. In
the second variation, no validation is performed on the value that is passed to the
`targetName` property of the `client` bean. Typos are therefore only discovered (with most
likely fatal results) when the `client` bean is actually instantiated. If the `client`
bean is a xref:core/beans/factory-scopes.adoc[prototype] bean, this typo and the resulting exception
may only be discovered long after the container is deployed.
bean is a xref:core/beans/factory-scopes.adoc[prototype] bean, this typo and the resulting
exception may only be discovered long after the container is deployed.
NOTE: The `local` attribute on the `idref` element is no longer supported in the 4.0 beans
XSD, since it does not provide value over a regular `bean` reference any more. Change
your existing `idref local` references to `idref bean` when upgrading to the 4.0 schema.
A common place (at least in versions earlier than Spring 2.0) where the `<idref/>` element
brings value is in the configuration of xref:core/aop-api/pfb.adoc#aop-pfb-1[AOP interceptors] in a
`ProxyFactoryBean` bean definition. Using `<idref/>` elements when you specify the
NOTE: A common place (at least in versions earlier than Spring 2.0) where the `<idref/>`
element brings value is in the configuration of xref:core/aop-api/pfb.adoc#aop-pfb-1[AOP interceptors]
in a `ProxyFactoryBean` bean definition. Using `<idref/>` elements when you specify the
interceptor names prevents you from misspelling an interceptor ID.
@@ -339,11 +339,11 @@ In the preceding scenario, using `@Autowired` works well and provides the desire
modularity, but determining exactly where the autowired bean definitions are declared is
still somewhat ambiguous. For example, as a developer looking at `ServiceConfig`, how do
you know exactly where the `@Autowired AccountRepository` bean is declared? It is not
explicit in the code, and this may be just fine. Remember that the
{spring-site-tools}[Spring Tools for Eclipse] provides tooling that
can render graphs showing how everything is wired, which may be all you need. Also,
your Java IDE can easily find all declarations and uses of the `AccountRepository` type
and quickly show you the location of `@Bean` methods that return that type.
explicit in the code, and this may be just fine. Note that the
{spring-site-tools}[Spring Tools] IDE support provides tooling that can render graphs
showing how everything is wired, which may be all you need. Also, your Java IDE can
easily find all declarations and uses of the `AccountRepository` type and quickly show
you the location of `@Bean` methods that return that type.
In cases where this ambiguity is not acceptable and you wish to have direct navigation
from within your IDE from one `@Configuration` class to another, consider autowiring the
@@ -7,14 +7,14 @@ similar to the https://jakarta.ee/specifications/expression-language/[Jakarta Ex
Language] but offers additional features, most notably method invocation and basic string
templating functionality.
While there are several other Java expression languages available -- OGNL, MVEL, and JBoss
EL, to name a few -- the Spring Expression Language was created to provide the Spring
community with a single well supported expression language that can be used across all
the products in the Spring portfolio. Its language features are driven by the
requirements of the projects in the Spring portfolio, including tooling requirements
for code completion support within the {spring-site-tools}[Spring Tools for Eclipse].
That said, SpEL is based on a technology-agnostic API that lets other expression language
implementations be integrated, should the need arise.
While there are several other Java expression languages available -- OGNL, MVEL, and
JBoss EL, to name a few -- the Spring Expression Language was created to provide the
Spring community with a single well supported expression language that can be used across
all the products in the Spring portfolio. Its language features are driven by the
requirements of the projects in the Spring portfolio, including tooling requirements for
code completion within the {spring-site-tools}[Spring Tools] IDE support. That said, SpEL
is based on a technology-agnostic API that lets other expression language implementations
be integrated, should the need arise.
While SpEL serves as the foundation for expression evaluation within the Spring
portfolio, it is not directly tied to Spring and can be used independently. To
@@ -676,7 +676,7 @@ provides `firstName` and `lastName` properties, such as the `Actor` class from a
[source,java,indent=0,subs="verbatim,quotes"]
----
this.jdbcClient.sql("insert into t_actor (first_name, last_name) values (:firstName, :lastName)")
.paramSource(new Actor("Leonor", "Watling")
.paramSource(new Actor("Leonor", "Watling"))
.update();
----
@@ -319,9 +319,17 @@ progresses.
== Testing
This section addresses testing with the combination of Kotlin and Spring Framework.
The recommended testing framework is https://junit.org/junit5/[JUnit 5] along with
The recommended testing framework is https://junit.org/[JUnit Jupiter] along with
https://mockk.io/[Mockk] for mocking.
[TIP]
====
Kotlin lets you specify meaningful test function names between backticks (```).
For a concrete example, see the `+++`Find all users on HTML page`()+++` test function later
in this section.
====
NOTE: If you are using Spring Boot, see
{spring-boot-docs-ref}/features/kotlin.html#features.kotlin.testing[this related documentation].
@@ -352,7 +360,6 @@ file with a `spring.test.constructor.autowire.mode = all` property.
[[per_class-lifecycle]]
=== `PER_CLASS` Lifecycle
Kotlin lets you specify meaningful test function names between backticks (```).
With JUnit Jupiter (JUnit 5), Kotlin test classes can use the `@TestInstance(TestInstance.Lifecycle.PER_CLASS)`
annotation to enable single instantiation of test classes, which allows the use of `@BeforeAll`
and `@AfterAll` annotations on non-static methods, which is a good fit for Kotlin.
@@ -187,7 +187,7 @@ default mode may be set via the
xref:appendix.adoc#appendix-spring-properties[`SpringProperties`] mechanism.
The default mode may also be configured as a
https://junit.org/junit5/docs/current/user-guide/#running-tests-config-params[JUnit Platform configuration parameter].
https://docs.junit.org/current/user-guide/#running-tests-config-params[JUnit Platform configuration parameter].
If the `spring.test.constructor.autowire.mode` property is not set, test class
constructors will not be automatically autowired.
@@ -77,6 +77,17 @@ exactly one candidate bean exists.
[TIP]
====
As stated in the documentation for Mockito, there are times when using `Mockito.when()` is
inappropriate for stubbing a spy for example, if calling a real method on a spy results
in undesired side effects.
To avoid such undesired side effects, consider using
`Mockito.doReturn(...).when(spy)...`, `Mockito.doThrow(...).when(spy)...`,
`Mockito.doNothing().when(spy)...`, and similar methods.
====
[NOTE]
====
Only _singleton_ beans can be overridden. Any attempt to override a non-singleton bean
will result in an exception.
@@ -5,24 +5,25 @@ It is important to be able to perform some integration testing without requiring
deployment to your application server or connecting to other enterprise infrastructure.
Doing so lets you test things such as:
* The correct wiring of your Spring IoC container contexts.
* Data access using JDBC or an ORM tool. This can include such things as the correctness
of SQL statements, Hibernate queries, JPA entity mappings, and so forth.
* The correct wiring of your Spring components.
* Data access using JDBC or an ORM tool.
** This can include such things as the correctness of SQL statements, Hibernate queries,
JPA entity mappings, and so forth.
The Spring Framework provides first-class support for integration testing in the
`spring-test` module. The name of the actual JAR file might include the release version
and might also be in the long `org.springframework.test` form, depending on where you get
it from (see the xref:core/beans/dependencies.adoc[section on Dependency Management]
for an explanation). This library includes the `org.springframework.test` package, which
`spring-test` module. The name of the actual JAR file might include the release version,
depending on where you get it from (see the
{spring-framework-wiki}/Spring-Framework-Artifacts[Spring Framework Artifacts] wiki page
for details). This library includes the `org.springframework.test` package, which
contains valuable classes for integration testing with a Spring container. This testing
does not rely on an application server or other deployment environment. Such tests are
slower to run than unit tests but much faster than the equivalent Selenium tests or
remote tests that rely on deployment to an application server.
Unit and integration testing support is provided in the form of the annotation-driven
xref:testing/testcontext-framework.adoc[Spring TestContext Framework]. The TestContext framework is
agnostic of the actual testing framework in use, which allows instrumentation of tests
in various environments, including JUnit, TestNG, and others.
xref:testing/testcontext-framework.adoc[Spring TestContext Framework]. The TestContext
framework is agnostic of the actual testing framework in use, which allows
instrumentation of tests in various environments, including JUnit, TestNG, and others.
The following section provides an overview of the high-level goals of Spring's
integration support, and the rest of this chapter then focuses on dedicated topics:
@@ -8,9 +8,9 @@ use https://www.gebish.org/[Geb] to make our tests even Groovy-er.
== Why Geb and MockMvc?
Geb is backed by WebDriver, so it offers many of the
xref:testing/mockmvc/htmlunit/webdriver.adoc#spring-mvc-test-server-htmlunit-webdriver-why[same benefits] that we get from
WebDriver. However, Geb makes things even easier by taking care of some of the
boilerplate code for us.
xref:testing/mockmvc/htmlunit/webdriver.adoc#mockmvc-server-htmlunit-webdriver-why[same benefits]
that we get from WebDriver. However, Geb makes things even easier by taking care of some
of the boilerplate code for us.
[[mockmvc-server-htmlunit-geb-setup]]
== MockMvc and Geb Setup
@@ -28,7 +28,8 @@ def setup() {
----
NOTE: This is a simple example of using `MockMvcHtmlUnitDriverBuilder`. For more advanced
usage, see xref:testing/mockmvc/htmlunit/webdriver.adoc#spring-mvc-test-server-htmlunit-webdriver-advanced-builder[Advanced `MockMvcHtmlUnitDriverBuilder`].
usage, see
xref:testing/mockmvc/htmlunit/webdriver.adoc#mockmvc-server-htmlunit-webdriver-advanced-builder[Advanced `MockMvcHtmlUnitDriverBuilder`].
This ensures that any URL referencing `localhost` as the server is directed to our
`MockMvc` instance without the need for a real HTTP connection. Any other URL is
@@ -62,10 +63,10 @@ forwarded to the current page object. This removes a lot of the boilerplate code
needed when using WebDriver directly.
As with direct WebDriver usage, this improves on the design of our
xref:testing/mockmvc/htmlunit/mah.adoc#spring-mvc-test-server-htmlunit-mah-usage[HtmlUnit test] by using the Page Object
Pattern. As mentioned previously, we can use the Page Object Pattern with HtmlUnit and
WebDriver, but it is even easier with Geb. Consider our new Groovy-based
`CreateMessagePage` implementation:
xref:testing/mockmvc/htmlunit/mah.adoc#mockmvc-server-htmlunit-mah-usage[HtmlUnit test]
by using the Page Object Pattern. As mentioned previously, we can use the Page Object
Pattern with HtmlUnit and WebDriver, but it is even easier with Geb. Consider our new
Groovy-based `CreateMessagePage` implementation:
[source,groovy]
----
@@ -7,8 +7,7 @@ to use the raw HtmlUnit libraries.
[[mockmvc-server-htmlunit-mah-setup]]
== MockMvc and HtmlUnit Setup
First, make sure that you have included a test dependency on
`org.htmlunit:htmlunit`.
First, make sure that you have included a test dependency on `org.htmlunit:htmlunit`.
We can easily create an HtmlUnit `WebClient` that integrates with MockMvc by using the
`MockMvcWebClientBuilder`, as follows:
@@ -45,7 +44,7 @@ Kotlin::
======
NOTE: This is a simple example of using `MockMvcWebClientBuilder`. For advanced usage,
see xref:testing/mockmvc/htmlunit/mah.adoc#spring-mvc-test-server-htmlunit-mah-advanced-builder[Advanced `MockMvcWebClientBuilder`].
see <<mockmvc-server-htmlunit-mah-advanced-builder>>.
This ensures that any URL that references `localhost` as the server is directed to our
`MockMvc` instance without the need for a real HTTP connection. Any other URL is
@@ -77,7 +76,7 @@ Kotlin::
======
NOTE: The default context path is `""`. Alternatively, we can specify the context path,
as described in xref:testing/mockmvc/htmlunit/mah.adoc#spring-mvc-test-server-htmlunit-mah-advanced-builder[Advanced `MockMvcWebClientBuilder`].
as described in <<mockmvc-server-htmlunit-mah-advanced-builder>>.
Once we have a reference to the `HtmlPage`, we can then fill out the form and submit it
to create a message, as the following example shows:
@@ -144,10 +143,10 @@ Kotlin::
======
The preceding code improves on our
xref:testing/mockmvc/htmlunit/why.adoc#spring-mvc-test-server-htmlunit-mock-mvc-test[MockMvc test] in a number of ways.
First, we no longer have to explicitly verify our form and then create a request that
looks like the form. Instead, we request the form, fill it out, and submit it, thereby
significantly reducing the overhead.
xref:testing/mockmvc/htmlunit/why.adoc#mockmvc-server-htmlunit-why[MockMvc test] in a
number of ways. First, we no longer have to explicitly verify our form and then create a
request that looks like the form. Instead, we request the form, fill it out, and submit
it, thereby significantly reducing the overhead.
Another important factor is that https://htmlunit.sourceforge.io/javascript.html[HtmlUnit
uses the Mozilla Rhino engine] to evaluate JavaScript. This means that we can also test
@@ -203,7 +203,7 @@ Kotlin::
======
NOTE: This is a simple example of using `MockMvcHtmlUnitDriverBuilder`. For more advanced
usage, see xref:testing/mockmvc/htmlunit/webdriver.adoc#spring-mvc-test-server-htmlunit-webdriver-advanced-builder[Advanced `MockMvcHtmlUnitDriverBuilder`].
usage, see <<mockmvc-server-htmlunit-webdriver-advanced-builder>>.
The preceding example ensures that any URL that references `localhost` as the server is
directed to our `MockMvc` instance without the need for a real HTTP connection. Any other
@@ -259,10 +259,11 @@ Kotlin::
======
--
This improves on the design of our xref:testing/mockmvc/htmlunit/mah.adoc#spring-mvc-test-server-htmlunit-mah-usage[HtmlUnit test]
This improves on the design of our
xref:testing/mockmvc/htmlunit/mah.adoc#mockmvc-server-htmlunit-mah-usage[HtmlUnit test]
by leveraging the Page Object Pattern. As we mentioned in
xref:testing/mockmvc/htmlunit/webdriver.adoc#spring-mvc-test-server-htmlunit-webdriver-why[Why WebDriver and MockMvc?], we can use the Page Object Pattern
with HtmlUnit, but it is much easier with WebDriver. Consider the following
<<mockmvc-server-htmlunit-webdriver-why>>, we can use the Page Object Pattern with
HtmlUnit, but it is much easier with WebDriver. Consider the following
`CreateMessagePage` implementation:
--
@@ -60,7 +60,7 @@ assume our form looks like the following snippet:
</form>
----
How do we ensure that our form produce the correct request to create a new message? A
How do we ensure that our form produces the correct request to create a new message? A
naive attempt might resemble the following:
[tabs]
@@ -154,7 +154,7 @@ validation.
[[mockmvc-server-htmlunit-why-integration]]
== Integration Testing to the Rescue?
To resolve the issues mentioned earlier, we could perform end-to-end integration testing,
To resolve the issues mentioned above, we could perform end-to-end integration testing,
but this has some drawbacks. Consider testing the view that lets us page through the
messages. We might need the following tests:
@@ -171,7 +171,7 @@ leads to a number of additional challenges:
* Testing can become slow, since each test would need to ensure that the database is in
the correct state.
* Since our database needs to be in a specific state, we cannot run tests in parallel.
* Performing assertions on such items as auto-generated IDs, timestamps, and others can
* Performing assertions on items such as auto-generated IDs, timestamps, and others can
be difficult.
These challenges do not mean that we should abandon end-to-end integration testing
@@ -2,10 +2,10 @@
= Application Events
The TestContext framework provides support for recording
xref:core/beans/context-introduction.adoc#context-functionality-events[application events] published in the
`ApplicationContext` so that assertions can be performed against those events within
tests. All events published during the execution of a single test are made available via
the `ApplicationEvents` API which allows you to process the events as a
xref:core/beans/context-introduction.adoc#context-functionality-events[application events]
published in the `ApplicationContext` so that assertions can be performed against those
events within tests. All events published during the execution of a single test are made
available via the `ApplicationEvents` API which allows you to process the events as a
`java.util.Stream`.
To use `ApplicationEvents` in your tests, do the following.
@@ -16,16 +16,23 @@ To use `ApplicationEvents` in your tests, do the following.
that `ApplicationEventsTestExecutionListener` is registered by default and only needs
to be manually registered if you have custom configuration via
`@TestExecutionListeners` that does not include the default listeners.
* Annotate a field of type `ApplicationEvents` with `@Autowired` and use that instance of
`ApplicationEvents` in your test and lifecycle methods (such as `@BeforeEach` and
`@AfterEach` methods in JUnit Jupiter).
** When using the xref:testing/testcontext-framework/support-classes.adoc#testcontext-junit-jupiter-extension[SpringExtension for JUnit Jupiter], you may declare a method
parameter of type `ApplicationEvents` in a test or lifecycle method as an alternative
to an `@Autowired` field in the test class.
* When using the
xref:testing/testcontext-framework/support-classes.adoc#testcontext-junit-jupiter-extension[SpringExtension for JUnit Jupiter],
declare a method parameter of type `ApplicationEvents` in a `@Test`, `@BeforeEach`, or
`@AfterEach` method.
** Since `ApplicationEvents` is scoped to the lifecycle of the current test method, this
is the recommended approach.
* Alternatively, you can annotate a field of type `ApplicationEvents` with `@Autowired`
and use that instance of `ApplicationEvents` in your test and lifecycle methods.
NOTE: `ApplicationEvents` is registered with the `ApplicationContext` as a _resolvable
dependency_ which is scoped to the lifecycle of the current test method. Consequently,
`ApplicationEvents` cannot be accessed outside the lifecycle of a test method and cannot be
`@Autowired` into the constructor of a test class.
The following test class uses the `SpringExtension` for JUnit Jupiter and
{assertj-docs}[AssertJ] to assert the types of application events
published while invoking a method in a Spring-managed component:
{assertj-docs}[AssertJ] to assert the types of application events published while
invoking a method in a Spring-managed component:
// Don't use "quotes" in the "subs" section because of the asterisks in /* ... */
[tabs]
@@ -38,16 +45,10 @@ Java::
@RecordApplicationEvents // <1>
class OrderServiceTests {
@Autowired
OrderService orderService;
@Autowired
ApplicationEvents events; // <2>
@Test
void submitOrder() {
void submitOrder(@Autowired OrderService service, ApplicationEvents events) { // <2>
// Invoke method in OrderService that publishes an event
orderService.submitOrder(new Order(/* ... */));
service.submitOrder(new Order(/* ... */));
// Verify that an OrderSubmitted event was published
long numEvents = events.stream(OrderSubmitted.class).count(); // <3>
assertThat(numEvents).isEqualTo(1);
@@ -66,16 +67,10 @@ Kotlin::
@RecordApplicationEvents // <1>
class OrderServiceTests {
@Autowired
lateinit var orderService: OrderService
@Autowired
lateinit var events: ApplicationEvents // <2>
@Test
fun submitOrder() {
fun submitOrder(@Autowired service: OrderService, events: ApplicationEvents) { // <2>
// Invoke method in OrderService that publishes an event
orderService.submitOrder(Order(/* ... */))
service.submitOrder(Order(/* ... */))
// Verify that an OrderSubmitted event was published
val numEvents = events.stream(OrderSubmitted::class).count() // <3>
assertThat(numEvents).isEqualTo(1)
@@ -22,7 +22,7 @@ TestNG:
* Dependency injection for test constructors, test methods, and test lifecycle callback
methods. See xref:testing/testcontext-framework/support-classes.adoc#testcontext-junit-jupiter-di[Dependency
Injection with the `SpringExtension`] for further details.
* Powerful support for link:https://junit.org/junit5/docs/current/user-guide/#extensions-conditions[conditional
* Powerful support for link:https://docs.junit.org/current/user-guide/#extensions-conditions[conditional
test execution] based on SpEL expressions, environment variables, system properties,
and so on. See the documentation for `@EnabledIf` and `@DisabledIf` in
xref:testing/annotations/integration-junit-jupiter.adoc[Spring JUnit Jupiter Testing Annotations]
@@ -160,7 +160,7 @@ for further details.
=== Dependency Injection with the `SpringExtension`
The `SpringExtension` implements the
link:https://junit.org/junit5/docs/current/user-guide/#extensions-parameter-resolution[`ParameterResolver`]
link:https://docs.junit.org/current/user-guide/#extensions-parameter-resolution[`ParameterResolver`]
extension API from JUnit Jupiter, which lets Spring provide dependency injection for test
constructors, test methods, and test lifecycle callback methods.
@@ -362,7 +362,7 @@ of `PlatformTransactionManager` within the test's `ApplicationContext`, you can
qualifier by using `@Transactional("myTxMgr")` or `@Transactional(transactionManager =
"myTxMgr")`, or `TransactionManagementConfigurer` can be implemented by an
`@Configuration` class. Consult the
{spring-framework-api}/test/context/transaction/TestContextTransactionUtils.html#retrieveTransactionManager-org.springframework.test.context.TestContext-java.lang.String-[javadoc
{spring-framework-api}/test/context/transaction/TestContextTransactionUtils.html#retrieveTransactionManager(org.springframework.test.context.TestContext,java.lang.String)[javadoc
for `TestContextTransactionUtils.retrieveTransactionManager()`] for details on the
algorithm used to look up a transaction manager in the test's `ApplicationContext`.
@@ -75,7 +75,7 @@ infrastructure and controller declarations and use it to handle requests via moc
and response objects, without a running server.
For WebFlux, use the following where the Spring `ApplicationContext` is passed to
{spring-framework-api}/web/server/adapter/WebHttpHandlerBuilder.html#applicationContext-org.springframework.context.ApplicationContext-[WebHttpHandlerBuilder]
{spring-framework-api}/web/server/adapter/WebHttpHandlerBuilder.html#applicationContext(org.springframework.context.ApplicationContext)[WebHttpHandlerBuilder]
to create the xref:web/webflux/reactive-spring.adoc#webflux-web-handler-api[WebHandler chain] to handle
requests:
@@ -44,7 +44,7 @@ rejected. No CORS headers are added to the responses of simple and actual CORS r
and, consequently, browsers reject them.
Each `HandlerMapping` can be
{spring-framework-api}/web/reactive/handler/AbstractHandlerMapping.html#setCorsConfigurations-java.util.Map-[configured]
{spring-framework-api}/web/reactive/handler/AbstractHandlerMapping.html#setCorsConfigurations(java.util.Map)[configured]
individually with URL pattern-based `CorsConfiguration` mappings. In most cases, applications
use the WebFlux Java configuration to declare such mappings, which results in a single,
global map passed to all `HandlerMapping` implementations.
@@ -57,7 +57,7 @@ class- or method-level `@CrossOrigin` annotations (other handlers can implement
The rules for combining global and local configuration are generally additive -- for example,
all global and all local origins. For those attributes where only a single value can be
accepted, such as `allowCredentials` and `maxAge`, the local overrides the global value. See
{spring-framework-api}/web/cors/CorsConfiguration.html#combine-org.springframework.web.cors.CorsConfiguration-[`CorsConfiguration#combine(CorsConfiguration)`]
{spring-framework-api}/web/cors/CorsConfiguration.html#combine(org.springframework.web.cors.CorsConfiguration)[`CorsConfiguration#combine(CorsConfiguration)`]
for more details.
[TIP]
@@ -294,7 +294,28 @@ allPartsEvents.windowUntil(PartEvent::isLast)
----
======
Note that the body contents of the `PartEvent` objects must be completely consumed, relayed, or released to avoid memory leaks.
NOTE: The body contents of the `PartEvent` objects must be completely consumed, relayed, or released to avoid memory leaks.
The following shows how to bind request parameters, including an optional `DataBinder` customization:
[tabs]
======
Java::
+
[source,java]
----
Pet pet = request.bind(Pet.class, dataBinder -> dataBinder.setAllowedFields("name"));
----
Kotlin::
+
[source,kotlin]
----
val pet = request.bind(Pet::class.java, {dataBinder -> dataBinder.setAllowedFields("name")})
----
======
[[webflux-fn-response]]
=== ServerResponse
@@ -448,7 +448,7 @@ Java::
----
@GetMapping
FragmentsRendering handle() {
return FragmentsRendering.with("posts").fragment("comments").build();
return FragmentsRendering.fragment("posts").fragment("comments").build();
}
----
@@ -458,7 +458,7 @@ Kotlin::
----
@GetMapping
fun handle(): FragmentsRendering {
return FragmentsRendering.with("posts").fragment("comments").build()
return FragmentsRendering.fragment("posts").fragment("comments").build()
}
----
======
@@ -2,18 +2,18 @@
= WebClient
:page-section-summary-toc: 1
Spring WebFlux includes a client to perform HTTP requests with. `WebClient` has a
functional, fluent API based on Reactor, see xref:web-reactive.adoc#webflux-reactive-libraries[Reactive Libraries],
Spring WebFlux includes a client to perform HTTP requests. `WebClient` has a
functional, fluent API based on Reactor (see xref:web/webflux-reactive-libraries.adoc[Reactive Libraries])
which enables declarative composition of asynchronous logic without the need to deal with
threads or concurrency. It is fully non-blocking, it supports streaming, and relies on
threads or concurrency. It is fully non-blocking, supports streaming, and relies on
the same xref:web/webflux/reactive-spring.adoc#webflux-codecs[codecs] that are also used to encode and
decode request and response content on the server side.
`WebClient` needs an HTTP client library to perform requests with. There is built-in
`WebClient` needs an HTTP client library to perform requests. There is built-in
support for the following:
* {reactor-github-org}/reactor-netty[Reactor Netty]
* {java-api}/java.net.http/java/net/http/HttpClient.html[JDK HttpClient]
* https://github.com/jetty-project/jetty-reactive-httpclient[Jetty Reactive HttpClient]
* https://hc.apache.org/index.html[Apache HttpComponents]
* Others can be plugged via `ClientHttpConnector`.
* Others can be plugged in via `ClientHttpConnector`.
@@ -310,7 +310,7 @@ Java::
Flux<String> source = ... ;
Mono<Void> output = session.send(source.map(session::textMessage)); <2>
return Mono.zip(input, output).then(); <3>
return input.and(output); <3>
}
}
----
@@ -338,7 +338,7 @@ Kotlin::
val source: Flux<String> = ...
val output = session.send(source.map(session::textMessage)) // <2>
return Mono.zip(input, output).then() // <3>
return input.and(output) // <3>
}
}
----
@@ -114,6 +114,6 @@ and others) and is equivalent to `required=false`.
| Any other argument
| If a method argument is not matched to any of the above, it is, by default, resolved as
a `@RequestParam` if it is a simple type, as determined by
{spring-framework-api}/beans/BeanUtils.html#isSimpleProperty-java.lang.Class-[BeanUtils#isSimpleProperty],
{spring-framework-api}/beans/BeanUtils.html#isSimpleProperty(java.lang.Class)[BeanUtils#isSimpleProperty],
or as a `@ModelAttribute`, otherwise.
|===
@@ -205,7 +205,7 @@ controller method xref:web/webmvc/mvc-controller/ann-validation.adoc[Validation]
TIP: Using `@ModelAttribute` is optional. By default, any argument that is not a simple
value type as determined by
{spring-framework-api}/beans/BeanUtils.html#isSimpleProperty-java.lang.Class-[BeanUtils#isSimpleProperty]
{spring-framework-api}/beans/BeanUtils.html#isSimpleProperty(java.lang.Class)[BeanUtils#isSimpleProperty]
_AND_ that is not resolved by any other argument resolver is treated as an implicit `@ModelAttribute`.
WARNING: When compiling to a native image with GraalVM, the implicit `@ModelAttribute`
@@ -74,6 +74,6 @@ When a `@RequestParam` annotation is declared on a `Map<String, String>` or
Note that use of `@RequestParam` is optional -- for example, to set its attributes. By
default, any argument that is a simple value type (as determined by
{spring-framework-api}/beans/BeanUtils.html#isSimpleProperty-java.lang.Class-[BeanUtils#isSimpleProperty])
{spring-framework-api}/beans/BeanUtils.html#isSimpleProperty(java.lang.Class)[BeanUtils#isSimpleProperty])
and is not resolved by any other argument resolver is treated as if it were annotated
with `@RequestParam`.
@@ -87,6 +87,6 @@ Reactor provides a dedicated operator for that, `Flux#collectList()`.
| Other return values
| If a return value remains unresolved in any other way, it is treated as a model
attribute, unless it is a simple type as determined by
{spring-framework-api}/beans/BeanUtils.html#isSimpleProperty-java.lang.Class-[BeanUtils#isSimpleProperty],
{spring-framework-api}/beans/BeanUtils.html#isSimpleProperty(java.lang.Class)[BeanUtils#isSimpleProperty],
in which case it remains unresolved.
|===
@@ -89,39 +89,7 @@ Kotlin::
You can map requests by using glob patterns and wildcards:
[cols="2,3,5"]
|===
|Pattern |Description |Example
| `+?+`
| Matches one character
| `+"/pages/t?st.html"+` matches `+"/pages/test.html"+` and `+"/pages/t3st.html"+`
| `+*+`
| Matches zero or more characters within a path segment
| `+"/resources/*.png"+` matches `+"/resources/file.png"+`
`+"/projects/*/versions"+` matches `+"/projects/spring/versions"+` but does not match `+"/projects/spring/boot/versions"+`
| `+**+`
| Matches zero or more path segments until the end of the path
| `+"/resources/**"+` matches `+"/resources/file.png"+` and `+"/resources/images/file.png"+`
`+"/resources/**/file.png"+` is invalid as `+**+` is only allowed at the end of the path.
| `+{name}+`
| Matches a path segment and captures it as a variable named "name"
| `+"/projects/{project}/versions"+` matches `+"/projects/spring/versions"+` and captures `+project=spring+`
| `+{name:[a-z]+}+`
| Matches the regexp `+"[a-z]+"+` as a path variable named "name"
| `+"/projects/{project:[a-z]+}/versions"+` matches `+"/projects/spring/versions"+` but not `+"/projects/spring1/versions"+`
| `+{*path}+`
| Matches zero or more path segments until the end of the path and captures it as a variable named "path"
| `+"/resources/{*file}"+` matches `+"/resources/images/file.png"+` and captures `+file=/images/file.png+`
|===
include::partial$web/uri-patterns.adoc[leveloffset=+1]
Captured URI variables can be accessed with `@PathVariable`, as the following example shows:
@@ -234,10 +202,13 @@ Kotlin::
======
--
URI path patterns can also have embedded `${...}` placeholders that are resolved on startup
by using `PropertySourcesPlaceholderConfigurer` against local, system, environment, and
other property sources. You can use this, for example, to parameterize a base URL based on
some external configuration.
URI path patterns can also have:
- Embedded `${...}` placeholders that are resolved on startup via
`PropertySourcesPlaceholderConfigurer` against local, system, environment, and
other property sources. This is useful, for example, to parameterize a base URL based on
external configuration.
- SpEL expressions `#{...}`.
NOTE: Spring WebFlux uses `PathPattern` and the `PathPatternParser` for URI path matching support.
Both classes are located in `spring-web` and are expressly designed for use with HTTP URL
@@ -7,19 +7,23 @@ Spring WebFlux has built-in xref:core/validation/validator.adoc[Validation] for
`@RequestMapping` methods, including xref:core/validation/beanvalidation.adoc[Java Bean Validation].
Validation may be applied at one of two levels:
1. xref:web/webflux/controller/ann-methods/modelattrib-method-args.adoc[@ModelAttribute],
1. Java Bean Validation is applied individually to an
xref:web/webflux/controller/ann-methods/modelattrib-method-args.adoc[@ModelAttribute],
xref:web/webflux/controller/ann-methods/requestbody.adoc[@RequestBody], and
xref:web/webflux/controller/ann-methods/multipart-forms.adoc[@RequestPart] argument
resolvers validate a method argument individually if the method parameter is annotated
with Jakarta `@Valid` or Spring's `@Validated`, _AND_ there is no `Errors` or
`BindingResult` parameter immediately after, _AND_ method validation is not needed (to be
discussed next). The exception raised in this case is `WebExchangeBindException`.
xref:web/webflux/controller/ann-methods/multipart-forms.adoc[@RequestPart] method parameter
annotated with `@jakarta.validation.Valid` or Spring's `@Validated` so long as
it is a command object rather than a container such as `Map` or `Collection`, it does not
have `Errors` or `BindingResult` immediately after in the method signature, and does not
otherwise require method validation (see next). `WebExchangeBindException` is the
exception raised when validating a method parameter individually.
2. When `@Constraint` annotations such as `@Min`, `@NotBlank` and others are declared
directly on method parameters, or on the method (for the return value), then method
validation must be applied, and that supersedes validation at the method argument level
because method validation covers both method parameter constraints and nested constraints
via `@Valid`. The exception raised in this case is `HandlerMethodValidationException`.
2. Java Bean Validation is applied to the method when `@Constraint` annotations such as
`@Min`, `@NotBlank` and others are declared directly on method parameters, or on the
method for the return value, and it supersedes any validation that would be applied
otherwise to a method parameter individually because method validation covers both
method parameter constraints and nested constraints via `@Valid`.
`HandlerMethodValidationException` is the exception raised validation is applied
to the method.
Applications must handle both `WebExchangeBindException` and
`HandlerMethodValidationException` as either may be raised depending on the controller
@@ -207,7 +207,7 @@ was not provided (for example, model attribute was returned) or an async return
view resolution scenarios. Explore the options in your IDE with code completion.
* `Model`, `Map`: Extra model attributes to be added to the model for the request.
* Any other: Any other return value (except for simple types, as determined by
{spring-framework-api}/beans/BeanUtils.html#isSimpleProperty-java.lang.Class-[BeanUtils#isSimpleProperty])
{spring-framework-api}/beans/BeanUtils.html#isSimpleProperty(java.lang.Class)[BeanUtils#isSimpleProperty])
is treated as a model attribute to be added to the model. The attribute name is derived
from the class name by using {spring-framework-api}/core/Conventions.html[conventions],
unless a handler method `@ModelAttribute` annotation is present.
@@ -15,27 +15,27 @@ See xref:integration/rest-clients.adoc#rest-restclient[`RestClient`] for more de
[[webmvc-webclient]]
== `WebClient`
`WebClient` is a reactive client to perform HTTP requests with a fluent API.
`WebClient` is a reactive client for making HTTP requests with a fluent API.
See xref:web/webflux-webclient.adoc[WebClient] for more details.
See xref:web/webflux-webclient.adoc[`WebClient`] for more details.
[[webmvc-resttemplate]]
== `RestTemplate`
`RestTemplate` is a synchronous client to perform HTTP requests. It is the original
`RestTemplate` is a synchronous client for making HTTP requests. It is the original
Spring REST client and exposes a simple, template-method API over underlying HTTP client
libraries.
See xref:integration/rest-clients.adoc[REST Endpoints] for details.
See xref:integration/rest-clients.adoc#rest-resttemplate[`RestTemplate`] for details.
[[webmvc-http-interface]]
== HTTP Interface
The Spring Frameworks lets you define an HTTP service as a Java interface with HTTP
The Spring Framework lets you define an HTTP service as a Java interface with HTTP
exchange methods. You can then generate a proxy that implements this interface and
performs the exchanges. This helps to simplify HTTP remote access and provides additional
flexibility for to choose an API style such as synchronous or reactive.
flexibility for choosing an API style such as synchronous or reactive.
See xref:integration/rest-clients.adoc#rest-http-interface[REST Endpoints] for details.
See xref:integration/rest-clients.adoc#rest-http-interface[HTTP Interface] for details.
@@ -71,7 +71,7 @@ rejected. No CORS headers are added to the responses of simple and actual CORS r
and, consequently, browsers reject them.
Each `HandlerMapping` can be
{spring-framework-api}/web/servlet/handler/AbstractHandlerMapping.html#setCorsConfigurations-java.util.Map-[configured]
{spring-framework-api}/web/servlet/handler/AbstractHandlerMapping.html#setCorsConfigurations(java.util.Map)[configured]
individually with URL pattern-based `CorsConfiguration` mappings. In most cases, applications
use the MVC Java configuration or the XML namespace to declare such mappings, which results
in a single global map being passed to all `HandlerMapping` instances.
@@ -84,7 +84,7 @@ class- or method-level `@CrossOrigin` annotations (other handlers can implement
The rules for combining global and local configuration are generally additive -- for example,
all global and all local origins. For those attributes where only a single value can be
accepted, for example, `allowCredentials` and `maxAge`, the local overrides the global value. See
{spring-framework-api}/web/cors/CorsConfiguration.html#combine-org.springframework.web.cors.CorsConfiguration-[`CorsConfiguration#combine(CorsConfiguration)`]
{spring-framework-api}/web/cors/CorsConfiguration.html#combine(org.springframework.web.cors.CorsConfiguration)[`CorsConfiguration#combine(CorsConfiguration)`]
for more details.
[TIP]
@@ -184,6 +184,26 @@ val map = request.params()
----
======
The following shows how to bind request parameters, including an optional `DataBinder` customization:
[tabs]
======
Java::
+
[source,java]
----
Pet pet = request.bind(Pet.class, dataBinder -> dataBinder.setAllowedFields("name"));
----
Kotlin::
+
[source,kotlin]
----
val pet = request.bind(Pet::class.java, {dataBinder -> dataBinder.setAllowedFields("name")})
----
======
[[webmvc-fn-response]]
=== ServerResponse
@@ -48,7 +48,7 @@ Java::
----
@GetMapping
FragmentsRendering handle() {
return FragmentsRendering.with("posts").fragment("comments").build();
return FragmentsRendering.fragment("posts").fragment("comments").build();
}
----
@@ -58,7 +58,7 @@ Kotlin::
----
@GetMapping
fun handle(): FragmentsRendering {
return FragmentsRendering.with("posts").fragment("comments").build()
return FragmentsRendering.fragment("posts").fragment("comments").build()
}
----
======
@@ -3,7 +3,10 @@
[.small]#xref:web/webflux/reactive-spring.adoc#webflux-filters[See equivalent in the Reactive stack]#
The `spring-web` module provides some useful filters:
In the Servlet API, you can add a `jakarta.servlet.Filter` to apply interception-style logic
before and after the rest of the processing chain of filters and the target `Servlet`.
The `spring-web` module has a number of built-in `Filter` implementations:
* xref:web/webmvc/filters.adoc#filters-http-put[Form Data]
* xref:web/webmvc/filters.adoc#filters-forwarded-headers[Forwarded Headers]
@@ -11,9 +14,19 @@ The `spring-web` module provides some useful filters:
* xref:web/webmvc/filters.adoc#filters-cors[CORS]
* xref:web/webmvc/filters.adoc#filters.url-handler[URL Handler]
Servlet filters can be configured in the `web.xml` configuration file or using Servlet annotations.
If you are using Spring Boot, you can
{spring-boot-docs}/how-to/webserver.html#howto.webserver.add-servlet-filter-listener.spring-bean[declare them as beans and configure them as part of your application].
There are also base class implementations for use in Spring applications:
* `GenericFilterBean` -- base class for a `Filter` configured as a Spring bean;
integrates with the Spring `ApplicationContext` lifecycle.
* `OncePerRequestFilter` -- extension of `GenericFilterBean` that supports a single
invocation at the start of a request, i.e. during the `REQUEST` dispatch phase, and
ignoring further handling via `FORWARD` dispatches. The filter also provides control
over whether the `Filter` gets involved in `ASYNC` and `ERROR` dispatches.
Servlet filters can be configured in `web.xml` or via Servlet annotations.
In a Spring Boot application , you can
{spring-boot-docs}/how-to/webserver.html#howto.webserver.add-servlet-filter-listener.spring-bean[declare Filter's as beans]
and Boot will have them configured.
[[filters-http-put]]
@@ -422,7 +422,7 @@ reactive types from the controller method.
Reactive return values are handled as follows:
* A single-value promise is adapted to, similar to using `DeferredResult`. Examples
include `CompletionStage` (JDK), Mono` (Reactor), and `Single` (RxJava).
include `CompletionStage` (JDK), `Mono` (Reactor), and `Single` (RxJava).
* A multi-value stream with a streaming media type (such as `application/x-ndjson`
or `text/event-stream`) is adapted to, similar to using `ResponseBodyEmitter` or
`SseEmitter`. Examples include `Flux` (Reactor) or `Observable` (RxJava).
@@ -175,7 +175,7 @@ Message codes and arguments for each error are also resolved via `MessageSource`
| `TypeMismatchException`
| (default)
| `+{0}+` property name, `+{1}+` property value
| `+{0}+` property name, `+{1}+` property value, `+{2}+` simple name of required type
| `UnsatisfiedServletRequestParameterException`
| (default)
@@ -215,7 +215,7 @@ the content negotiation during the error handling phase will decide which conten
| Any other return value
| If a return value is not matched to any of the above and is not a simple type (as determined by
{spring-framework-api}/beans/BeanUtils.html#isSimpleProperty-java.lang.Class-[BeanUtils#isSimpleProperty]),
{spring-framework-api}/beans/BeanUtils.html#isSimpleProperty(java.lang.Class)[BeanUtils#isSimpleProperty]),
by default, it is treated as a model attribute to be added to the model. If it is a simple type,
it remains unresolved.
|===
@@ -135,6 +135,6 @@ and others) and is equivalent to `required=false`.
| Any other argument
| If a method argument is not matched to any of the earlier values in this table and it is
a simple type (as determined by
{spring-framework-api}/beans/BeanUtils.html#isSimpleProperty-java.lang.Class-[BeanUtils#isSimpleProperty]),
{spring-framework-api}/beans/BeanUtils.html#isSimpleProperty(java.lang.Class)[BeanUtils#isSimpleProperty]),
it is resolved as a `@RequestParam`. Otherwise, it is resolved as a `@ModelAttribute`.
|===
@@ -250,7 +250,7 @@ xref:web/webmvc/mvc-controller/ann-validation.adoc[Validation].
TIP: Using `@ModelAttribute` is optional. By default, any parameter that is not a simple
value type as determined by
{spring-framework-api}/beans/BeanUtils.html#isSimpleProperty-java.lang.Class-[BeanUtils#isSimpleProperty]
{spring-framework-api}/beans/BeanUtils.html#isSimpleProperty(java.lang.Class)[BeanUtils#isSimpleProperty]
_AND_ that is not resolved by any other argument resolver is treated as an implicit `@ModelAttribute`.
WARNING: When compiling to a native image with GraalVM, the implicit `@ModelAttribute`
@@ -117,6 +117,6 @@ Kotlin::
Note that use of `@RequestParam` is optional (for example, to set its attributes).
By default, any argument that is a simple value type (as determined by
{spring-framework-api}/beans/BeanUtils.html#isSimpleProperty-java.lang.Class-[BeanUtils#isSimpleProperty])
{spring-framework-api}/beans/BeanUtils.html#isSimpleProperty(java.lang.Class)[BeanUtils#isSimpleProperty])
and is not resolved by any other argument resolver, is treated as if it were annotated
with `@RequestParam`.
@@ -98,6 +98,6 @@ supported for all return values.
| Other return values
| If a return value remains unresolved in any other way, it is treated as a model
attribute, unless it is a simple type as determined by
{spring-framework-api}/beans/BeanUtils.html#isSimpleProperty-java.lang.Class-[BeanUtils#isSimpleProperty],
{spring-framework-api}/beans/BeanUtils.html#isSimpleProperty(java.lang.Class)[BeanUtils#isSimpleProperty],
in which case it remains unresolved.
|===
@@ -103,22 +103,9 @@ Spring WebFlux. It was enabled for use in Spring MVC from version 5.3 and is ena
default from version 6.0. See xref:web/webmvc/mvc-config/path-matching.adoc[MVC config] for
customizations of path matching options.
`PathPattern` supports the same pattern syntax as `AntPathMatcher`. In addition, it also
supports the capturing pattern, for example, `+{*spring}+`, for matching 0 or more path segments
at the end of a path. `PathPattern` also restricts the use of `+**+` for matching multiple
path segments such that it's only allowed at the end of a pattern. This eliminates many
cases of ambiguity when choosing the best matching pattern for a given request.
For full pattern syntax please refer to
{spring-framework-api}/web/util/pattern/PathPattern.html[PathPattern] and
{spring-framework-api}/util/AntPathMatcher.html[AntPathMatcher].
You can map requests by using glob patterns and wildcards:
Some example patterns:
* `+"/resources/ima?e.png"+` - match one character in a path segment
* `+"/resources/*.png"+` - match zero or more characters in a path segment
* `+"/resources/**"+` - match multiple path segments
* `+"/projects/{project}/versions"+` - match a path segment and capture it as a variable
* `++"/projects/{project:[a-z]+}/versions"++` - match and capture a variable with a regex
include::partial$web/uri-patterns.adoc[leveloffset=+1]
Captured URI variables can be accessed with `@PathVariable`. For example:
@@ -217,10 +204,13 @@ Kotlin::
----
======
URI path patterns can also have embedded `${...}` placeholders that are resolved on startup
by using `PropertySourcesPlaceholderConfigurer` against local, system, environment, and
other property sources. You can use this, for example, to parameterize a base URL based on
some external configuration.
URI path patterns can also have:
- Embedded `${...}` placeholders that are resolved on startup via
`PropertySourcesPlaceholderConfigurer` against local, system, environment, and
other property sources. This is useful, for example, to parameterize a base URL based on
external configuration.
- SpEL expression `#{...}`.
[[mvc-ann-requestmapping-pattern-comparison]]
@@ -231,7 +221,7 @@ When multiple patterns match a URL, the best match must be selected. This is don
one of the following depending on whether use of parsed `PathPattern` is enabled for use or not:
* {spring-framework-api}/web/util/pattern/PathPattern.html#SPECIFICITY_COMPARATOR[`PathPattern.SPECIFICITY_COMPARATOR`]
* {spring-framework-api}/util/AntPathMatcher.html#getPatternComparator-java.lang.String-[`AntPathMatcher.getPatternComparator(String path)`]
* {spring-framework-api}/util/AntPathMatcher.html#getPatternComparator(java.lang.String)[`AntPathMatcher.getPatternComparator(String path)`]
Both help to sort patterns with more specific ones on top. A pattern is more specific if
it has a lower count of URI variables (counted as 1), single wildcards (counted as 1),
@@ -7,22 +7,26 @@ Spring MVC has built-in xref:core/validation/validator.adoc[validation] for
`@RequestMapping` methods, including xref:core/validation/beanvalidation.adoc[Java Bean Validation].
Validation may be applied at one of two levels:
1. xref:web/webmvc/mvc-controller/ann-methods/modelattrib-method-args.adoc[@ModelAttribute],
1. Java Bean Validation is applied individually to an
xref:web/webmvc/mvc-controller/ann-methods/modelattrib-method-args.adoc[@ModelAttribute],
xref:web/webmvc/mvc-controller/ann-methods/requestbody.adoc[@RequestBody], and
xref:web/webmvc/mvc-controller/ann-methods/multipart-forms.adoc[@RequestPart] argument
resolvers validate a method argument individually if the method parameter is annotated
with Jakarta `@Valid` or Spring's `@Validated`, _AND_ there is no `Errors` or
`BindingResult` parameter immediately after, _AND_ method validation is not needed (to be
discussed next). The exception raised in this case is `MethodArgumentNotValidException`.
xref:web/webmvc/mvc-controller/ann-methods/multipart-forms.adoc[@RequestPart] method parameter
annotated with `@jakarta.validation.Valid` or Spring's `@Validated` so long as
it is a command object rather than a container such as `Map` or `Collection`, it does not
have `Errors` or `BindingResult` immediately after in the method signature, and does not
otherwise require method validation (see next). `MethodArgumentNotValidException` is the
exception raised when validating a method parameter individually.
2. When `@Constraint` annotations such as `@Min`, `@NotBlank` and others are declared
directly on method parameters, or on the method (for the return value), then method
validation must be applied, and that supersedes validation at the method argument level
because method validation covers both method parameter constraints and nested constraints
via `@Valid`. The exception raised in this case is `HandlerMethodValidationException`.
2. Java Bean Validation is applied to the method when `@Constraint` annotations such as
`@Min`, `@NotBlank` and others are declared directly on method parameters, or on the
method for the return value, and it supersedes any validation that would be applied
otherwise to a method parameter individually because method validation covers both
method parameter constraints and nested constraints via `@Valid`.
`HandlerMethodValidationException` is the exception raised validation is applied
to the method.
Applications must handle both `MethodArgumentNotValidException` and
`HandlerMethodValidationException` as either may be raised depending on the controller
Applications should handle both `MethodArgumentNotValidException` and
`HandlerMethodValidationException` since either may be raised depending on the controller
method signature. The two exceptions, however are designed to be very similar, and can be
handled with almost identical code. The main difference is that the former is for a single
object while the latter is for a list of method parameters.
@@ -0,0 +1,51 @@
[cols="2,3,5"]
|===
|Pattern |Description |Example
| `spring`
| Literal pattern
| `+"/spring"+` matches `+"/spring"+`
| `+?+`
| Matches one character
| `+"/pages/t?st.html"+` matches `+"/pages/test.html"+` and `+"/pages/t3st.html"+`
| `+*+`
| Matches zero or more characters within a path segment
| `+"/resources/*.png"+` matches `+"/resources/file.png"+`
`+"/projects/*/versions"+` matches `+"/projects/spring/versions"+` but does not match `+"/projects/spring/boot/versions"+`.
`+"/projects/*"+` matches `+"/projects/spring"+` but does not match `+"/projects"+` as the path segment is not present.
| `+**+`
| Matches zero or more path segments
| `+"/resources/**"+` matches `+"/resources"+`, `+"/resources/file.png"+` and `+"/resources/images/file.png"+`
`+"/**/info"+` matches `+"/info"+`, `+"/spring/info"+` and `+"/spring/framework/info"+`
`+"/resources/**/file.png"+` is invalid as `+**+` is not allowed in the middle of the path.
`+"/**/spring/**"+` is not allowed, as only a single `+**+`/`+{*path}+` instance is allowed per pattern.
| `+{name}+`
| Similar to `+*+`, but also captures the path segment as a variable named "name"
| `+"/projects/{project}/versions"+` matches `+"/projects/spring/versions"+` and captures `+project=spring+`
`+"/projects/{project}/versions"+` does not match `+"/projects/spring/framework/versions"+` as it captures a single path segment.
| `{name:[a-z]+}`
| Matches the regexp `"[a-z]+"` as a path variable named "name"
| `"/projects/{project:[a-z]+}/versions"` matches `"/projects/spring/versions"` but not `"/projects/spring1/versions"`
| `+{*path}+`
| Similar to `+**+`, but also captures the path segments as a variable named "path"
| `+"/resources/{*file}"+` matches `+"/resources/images/file.png"+` and captures `+file=/images/file.png+`
`+"{*path}/resources"+` matches `+"/spring/framework/resources"+` and captures `+path=/spring/framework+`
`+"/resources/{*path}/file.png"+` is invalid as `{*path}` is not allowed in the middle of the path.
`+"/{*path}/spring/**"+` is not allowed, as only a single `+**+`/`+{*path}+` instance is allowed per pattern.
|===
+1 -1
View File
@@ -4,7 +4,7 @@
"@antora/atlas-extension": "1.0.0-alpha.2",
"@antora/collector-extension": "1.0.0-alpha.3",
"@asciidoctor/tabs": "1.0.0-beta.6",
"@springio/antora-extensions": "1.14.2",
"@springio/antora-extensions": "1.14.7",
"fast-xml-parser": "4.5.2",
"@springio/asciidoctor-extensions": "1.0.0-alpha.10"
}
+35 -35
View File
@@ -7,33 +7,33 @@ javaPlatform {
}
dependencies {
api(platform("com.fasterxml.jackson:jackson-bom:2.18.4"))
api(platform("io.micrometer:micrometer-bom:1.14.9"))
api(platform("io.netty:netty-bom:4.1.123.Final"))
api(platform("com.fasterxml.jackson:jackson-bom:2.18.5"))
api(platform("io.micrometer:micrometer-bom:1.14.14"))
api(platform("io.netty:netty-bom:4.1.128.Final"))
api(platform("io.netty:netty5-bom:5.0.0.Alpha5"))
api(platform("io.projectreactor:reactor-bom:2024.0.8"))
api(platform("io.projectreactor:reactor-bom:2024.0.13"))
api(platform("io.rsocket:rsocket-bom:1.1.5"))
api(platform("org.apache.groovy:groovy-bom:4.0.27"))
api(platform("org.apache.groovy:groovy-bom:4.0.29"))
api(platform("org.apache.logging.log4j:log4j-bom:2.21.1"))
api(platform("org.assertj:assertj-bom:3.27.3"))
api(platform("org.eclipse.jetty:jetty-bom:12.0.23"))
api(platform("org.eclipse.jetty.ee10:jetty-ee10-bom:12.0.23"))
api(platform("org.assertj:assertj-bom:3.27.6"))
api(platform("org.eclipse.jetty:jetty-bom:12.0.30"))
api(platform("org.eclipse.jetty.ee10:jetty-ee10-bom:12.0.30"))
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.13.3"))
api(platform("org.mockito:mockito-bom:5.18.0"))
api(platform("org.junit:junit-bom:5.14.1"))
api(platform("org.mockito:mockito-bom:5.20.0"))
constraints {
api("com.fasterxml:aalto-xml:1.3.2")
api("com.fasterxml:aalto-xml:1.3.4")
api("com.fasterxml.woodstox:woodstox-core:6.7.0")
api("com.github.ben-manes.caffeine:caffeine:3.2.1")
api("com.github.ben-manes.caffeine:caffeine:3.2.3")
api("com.github.librepdf:openpdf:1.3.43")
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.13.1")
api("com.google.protobuf:protobuf-java-util:4.30.2")
api("com.google.code.gson:gson:2.13.2")
api("com.google.protobuf:protobuf-java-util:4.32.1")
api("com.h2database:h2:2.3.232")
api("com.jayway.jsonpath:json-path:2.9.0")
api("com.jayway.jsonpath:json-path:2.10.0")
api("com.oracle.database.jdbc:ojdbc11:21.9.0.0")
api("com.rometools:rome:1.19.0")
api("com.squareup.okhttp3:mockwebserver:3.14.9")
@@ -53,11 +53,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.10")
api("io.reactivex.rxjava3:rxjava:3.1.12")
api("io.smallrye.reactive:mutiny:1.10.0")
api("io.undertow:undertow-core:2.3.18.Final")
api("io.undertow:undertow-servlet:2.3.18.Final")
api("io.undertow:undertow-websockets-jsr:2.3.18.Final")
api("io.undertow:undertow-core:2.3.20.Final")
api("io.undertow:undertow-servlet:2.3.20.Final")
api("io.undertow:undertow-websockets-jsr:2.3.20.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")
@@ -90,17 +90,17 @@ dependencies {
api("junit:junit:4.13.2")
api("net.sf.jopt-simple:jopt-simple:5.0.4")
api("org.apache-extras.beanshell:bsh:2.0b6")
api("org.apache.activemq:activemq-broker:5.17.6")
api("org.apache.activemq:activemq-kahadb-store:5.17.6")
api("org.apache.activemq:activemq-stomp:5.17.6")
api("org.apache.activemq:artemis-jakarta-client:2.31.2")
api("org.apache.activemq:artemis-junit-5:2.31.2")
api("org.apache.activemq:activemq-broker:5.17.7")
api("org.apache.activemq:activemq-kahadb-store:5.17.7")
api("org.apache.activemq:activemq-stomp:5.17.7")
api("org.apache.activemq:artemis-jakarta-client:2.42.0")
api("org.apache.activemq:artemis-junit-5:2.42.0")
api("org.apache.commons:commons-pool2:2.9.0")
api("org.apache.derby:derby:10.16.1.1")
api("org.apache.derby:derbyclient:10.16.1.1")
api("org.apache.derby:derbytools:10.16.1.1")
api("org.apache.httpcomponents.client5:httpclient5:5.5")
api("org.apache.httpcomponents.core5:httpcore5-reactive:5.3.4")
api("org.apache.httpcomponents.core5:httpcore5-reactive:5.3.5")
api("org.apache.poi:poi-ooxml:5.2.5")
api("org.apache.tomcat.embed:tomcat-embed-core:10.1.28")
api("org.apache.tomcat.embed:tomcat-embed-websocket:10.1.28")
@@ -113,9 +113,9 @@ dependencies {
api("org.bouncycastle:bcpkix-jdk18on:1.72")
api("org.codehaus.jettison:jettison:1.5.4")
api("org.crac:crac:1.4.0")
api("org.dom4j:dom4j:2.1.4")
api("org.easymock:easymock:5.5.0")
api("org.eclipse.jetty:jetty-reactive-httpclient:4.0.9")
api("org.dom4j:dom4j:2.2.0")
api("org.easymock:easymock:5.6.0")
api("org.eclipse.jetty:jetty-reactive-httpclient:4.0.12")
api("org.eclipse.persistence:org.eclipse.persistence.jpa:3.0.4")
api("org.eclipse:yasson:2.0.4")
api("org.ehcache:ehcache:3.10.8")
@@ -129,24 +129,24 @@ dependencies {
api("org.hibernate:hibernate-core-jakarta:5.6.15.Final")
api("org.hibernate:hibernate-validator:7.0.5.Final")
api("org.hsqldb:hsqldb:2.7.4")
api("org.htmlunit:htmlunit:4.13.0")
api("org.htmlunit:htmlunit:4.18.0")
api("org.javamoney:moneta:1.4.4")
api("org.jruby:jruby:9.4.12.0")
api("org.jruby:jruby:9.4.13.0")
api("org.junit.support:testng-engine:1.0.5")
api("org.mozilla:rhino:1.7.15")
api("org.ogce:xpp3:1.1.6")
api("org.python:jython-standalone:2.7.4")
api("org.quartz-scheduler:quartz:2.3.2")
api("org.seleniumhq.selenium:htmlunit3-driver:4.33.0")
api("org.seleniumhq.selenium:selenium-java:4.34.0")
api("org.seleniumhq.selenium:htmlunit3-driver:4.38.0")
api("org.seleniumhq.selenium:selenium-java:4.38.0")
api("org.skyscreamer:jsonassert:1.5.3")
api("org.slf4j:slf4j-api:2.0.17")
api("org.testng:testng:7.11.0")
api("org.webjars:underscorejs:1.8.3")
api("org.webjars:webjars-locator-core:0.59")
api("org.webjars:webjars-locator-lite:1.1.0")
api("org.xmlunit:xmlunit-assertj:2.10.3")
api("org.xmlunit:xmlunit-matchers:2.10.3")
api("org.yaml:snakeyaml:2.4")
api("org.xmlunit:xmlunit-assertj:2.10.4")
api("org.xmlunit:xmlunit-matchers:2.10.4")
api("org.yaml:snakeyaml:2.5")
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
version=6.2.9-SNAPSHOT
version=6.2.15
org.gradle.caching=true
org.gradle.jvmargs=-Xmx2048m
@@ -62,7 +62,7 @@ public interface ProxyMethodInvocation extends MethodInvocation {
MethodInvocation invocableClone(Object... arguments);
/**
* Set the arguments to be used on subsequent invocations in the any advice
* Set the arguments to be used on subsequent invocations in any advice
* in this chain.
* @param arguments the argument array
*/
@@ -121,12 +121,12 @@ public abstract class AopConfigUtils {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
if (registry.containsBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME)) {
BeanDefinition apcDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
if (!cls.getName().equals(apcDefinition.getBeanClassName())) {
int currentPriority = findPriorityForClass(apcDefinition.getBeanClassName());
BeanDefinition beanDefinition = registry.getBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME);
if (!cls.getName().equals(beanDefinition.getBeanClassName())) {
int currentPriority = findPriorityForClass(beanDefinition.getBeanClassName());
int requiredPriority = findPriorityForClass(cls);
if (currentPriority < requiredPriority) {
apcDefinition.setBeanClassName(cls.getName());
beanDefinition.setBeanClassName(cls.getName());
}
}
return null;
@@ -134,8 +134,8 @@ public abstract class AopConfigUtils {
RootBeanDefinition beanDefinition = new RootBeanDefinition(cls);
beanDefinition.setSource(source);
beanDefinition.getPropertyValues().add("order", Ordered.HIGHEST_PRECEDENCE);
beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
beanDefinition.getPropertyValues().add("order", Ordered.HIGHEST_PRECEDENCE);
registry.registerBeanDefinition(AUTO_PROXY_CREATOR_BEAN_NAME, beanDefinition);
return beanDefinition;
}
@@ -117,6 +117,7 @@ public abstract class AbstractAdvisingBeanPostProcessor extends ProxyProcessorSu
}
proxyFactory.addAdvisor(this.advisor);
customizeProxyFactory(proxyFactory);
proxyFactory.setPreFiltered(true);
// Use original ClassLoader if bean class not locally loaded in overriding class loader
ClassLoader classLoader = getProxyClassLoader();
@@ -41,8 +41,8 @@ abstract class CoroutinesUtils {
}
}
@SuppressWarnings({"rawtypes", "unchecked"})
@Nullable
@SuppressWarnings({"unchecked", "rawtypes"})
static Object awaitSingleOrNull(@Nullable Object value, Object continuation) {
return MonoKt.awaitSingleOrNull(value instanceof Mono mono ? mono : Mono.justOrEmpty(value),
(Continuation<Object>) continuation);
@@ -24,9 +24,9 @@ import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.lang.Nullable;
/**
* Extension of {@link AbstractAutoProxyCreator} which implements {@link BeanFactoryAware},
* adds exposure of the original target class for each proxied bean
* ({@link AutoProxyUtils#ORIGINAL_TARGET_CLASS_ATTRIBUTE}),
* Extension of {@link AbstractAdvisingBeanPostProcessor} which implements
* {@link BeanFactoryAware}, adds exposure of the original target class for each
* proxied bean ({@link AutoProxyUtils#ORIGINAL_TARGET_CLASS_ATTRIBUTE}),
* and participates in an externally enforced target-class mode for any given bean
* ({@link AutoProxyUtils#PRESERVE_TARGET_CLASS_ATTRIBUTE}).
* This post-processor is therefore aligned with {@link AbstractAutoProxyCreator}.
@@ -81,13 +81,19 @@ public abstract class ScopedProxyUtils {
// Copy autowire settings from original bean definition.
proxyDefinition.setAutowireCandidate(targetDefinition.isAutowireCandidate());
proxyDefinition.setPrimary(targetDefinition.isPrimary());
proxyDefinition.setFallback(targetDefinition.isFallback());
if (targetDefinition instanceof AbstractBeanDefinition abd) {
proxyDefinition.setDefaultCandidate(abd.isDefaultCandidate());
proxyDefinition.copyQualifiersFrom(abd);
}
// The target bean should be ignored in favor of the scoped proxy.
targetDefinition.setAutowireCandidate(false);
targetDefinition.setPrimary(false);
targetDefinition.setFallback(false);
if (targetDefinition instanceof AbstractBeanDefinition abd) {
abd.setDefaultCandidate(false);
}
// Register the target bean as separate bean in the factory.
registry.registerBeanDefinition(targetBeanName, targetDefinition);
@@ -37,7 +37,6 @@ import static org.mockito.Mockito.verify;
* Tests for {@link AsyncExecutionInterceptor}.
*
* @author Bao Ngo
* @since 7.0
*/
class AsyncExecutionInterceptorTests {
@@ -62,11 +61,13 @@ class AsyncExecutionInterceptorTests {
O run();
}
static class FutureRunner implements GenericRunner<Future<Void>> {
@Override
public Future<Void> run() {
return CompletableFuture.runAsync(() -> {
});
return CompletableFuture.runAsync(() -> {});
}
}
}
@@ -18,6 +18,15 @@ package org.springframework.aop.scope;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.AutowireCandidateQualifier;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.support.SimpleBeanDefinitionRegistry;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
@@ -25,6 +34,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
* Tests for {@link ScopedProxyUtils}.
*
* @author Sam Brannen
* @author Juergen Hoeller
* @since 5.1.10
*/
class ScopedProxyUtilsTests {
@@ -53,15 +63,79 @@ class ScopedProxyUtilsTests {
@Test
void getOriginalBeanNameForNullTargetBean() {
assertThatIllegalArgumentException()
.isThrownBy(() -> ScopedProxyUtils.getOriginalBeanName(null))
.withMessage("bean name 'null' does not refer to the target of a scoped proxy");
.isThrownBy(() -> ScopedProxyUtils.getOriginalBeanName(null))
.withMessage("bean name 'null' does not refer to the target of a scoped proxy");
}
@Test
void getOriginalBeanNameForNonScopedTarget() {
assertThatIllegalArgumentException()
.isThrownBy(() -> ScopedProxyUtils.getOriginalBeanName("myBean"))
.withMessage("bean name 'myBean' does not refer to the target of a scoped proxy");
.isThrownBy(() -> ScopedProxyUtils.getOriginalBeanName("myBean"))
.withMessage("bean name 'myBean' does not refer to the target of a scoped proxy");
}
@Test
void createScopedProxyTargetAppliesAutowireSettingsToProxyBeanDefinition() {
AbstractBeanDefinition targetDefinition = new GenericBeanDefinition();
// Opposite of defaults
targetDefinition.setAutowireCandidate(false);
targetDefinition.setDefaultCandidate(false);
targetDefinition.setPrimary(true);
targetDefinition.setFallback(true);
BeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry();
BeanDefinitionHolder proxyHolder = ScopedProxyUtils.createScopedProxy(
new BeanDefinitionHolder(targetDefinition, "myBean"), registry, false);
AbstractBeanDefinition proxyBeanDefinition = (AbstractBeanDefinition) proxyHolder.getBeanDefinition();
assertThat(proxyBeanDefinition.isAutowireCandidate()).isFalse();
assertThat(proxyBeanDefinition.isDefaultCandidate()).isFalse();
assertThat(proxyBeanDefinition.isPrimary()).isTrue();
assertThat(proxyBeanDefinition.isFallback()).isTrue();
}
@Test
void createScopedProxyTargetAppliesBeanAttributesToProxyBeanDefinition() {
GenericBeanDefinition targetDefinition = new GenericBeanDefinition();
// Opposite of defaults
targetDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
targetDefinition.setSource("theSource");
targetDefinition.addQualifier(new AutowireCandidateQualifier("myQualifier"));
BeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry();
BeanDefinitionHolder proxyHolder = ScopedProxyUtils.createScopedProxy(
new BeanDefinitionHolder(targetDefinition, "myBean"), registry, false);
BeanDefinition proxyBeanDefinition = proxyHolder.getBeanDefinition();
assertThat(proxyBeanDefinition.getRole()).isEqualTo(BeanDefinition.ROLE_INFRASTRUCTURE);
assertThat(proxyBeanDefinition).isInstanceOf(RootBeanDefinition.class);
assertThat(proxyBeanDefinition.getPropertyValues()).hasSize(2);
assertThat(proxyBeanDefinition.getPropertyValues().get("proxyTargetClass")).isEqualTo(false);
assertThat(proxyBeanDefinition.getPropertyValues().get("targetBeanName")).isEqualTo(
ScopedProxyUtils.getTargetBeanName("myBean"));
RootBeanDefinition rootBeanDefinition = (RootBeanDefinition) proxyBeanDefinition;
assertThat(rootBeanDefinition.getQualifiers()).hasSize(1);
assertThat(rootBeanDefinition.hasQualifier("myQualifier")).isTrue();
assertThat(rootBeanDefinition.getSource()).isEqualTo("theSource");
}
@Test
void createScopedProxyTargetCleansAutowireSettingsInTargetDefinition() {
AbstractBeanDefinition targetDefinition = new GenericBeanDefinition();
targetDefinition.setAutowireCandidate(true);
targetDefinition.setDefaultCandidate(true);
targetDefinition.setPrimary(true);
targetDefinition.setFallback(true);
BeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry();
ScopedProxyUtils.createScopedProxy(
new BeanDefinitionHolder(targetDefinition, "myBean"), registry, false);
assertThat(targetDefinition.isAutowireCandidate()).isFalse();
assertThat(targetDefinition.isDefaultCandidate()).isFalse();
assertThat(targetDefinition.isPrimary()).isFalse();
assertThat(targetDefinition.isFallback()).isFalse();
}
}
@@ -19,6 +19,7 @@ package org.springframework.aop.framework
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.jupiter.api.Test
import java.time.LocalDateTime
/**
* Tests for Kotlin support in [CglibAopProxy].
@@ -48,6 +49,13 @@ class CglibAopProxyKotlinTests {
assertThatThrownBy { proxy.checkedException() }.isInstanceOf(CheckedException::class.java)
}
@Test // gh-35487
fun jvmDefault() {
val proxyFactory = ProxyFactory()
proxyFactory.setTarget(AddressRepo())
proxyFactory.proxy
}
open class MyKotlinBean {
@@ -63,4 +71,24 @@ class CglibAopProxyKotlinTests {
}
class CheckedException() : Exception()
open class AddressRepo(): CrudRepo<Address, Int>
interface CrudRepo<E : Any, ID : Any> {
fun save(e: E): E {
return e
}
fun delete(id: ID): Long {
return 0L
}
}
data class Address(
val id: Int = 0,
val street: String,
val version: Int = 0,
val createdAt: LocalDateTime? = null,
val updatedAt: LocalDateTime? = null,
)
}
@@ -566,7 +566,7 @@ public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationA
}
final List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
Class<?> targetClass = clazz;
Class<?> targetClass = ClassUtils.getUserClass(clazz);
do {
final List<InjectionMetadata.InjectedElement> fieldElements = new ArrayList<>();
@@ -586,12 +586,11 @@ public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationA
final List<InjectionMetadata.InjectedElement> methodElements = new ArrayList<>();
ReflectionUtils.doWithLocalMethods(targetClass, method -> {
Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
if (method.isBridge()) {
return;
}
MergedAnnotation<?> ann = findAutowiredAnnotation(bridgedMethod);
if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
MergedAnnotation<?> ann = findAutowiredAnnotation(method);
if (ann != null && method.equals(BridgeMethodResolver.getMostSpecificMethod(method, clazz))) {
if (Modifier.isStatic(method.getModifiers())) {
if (logger.isInfoEnabled()) {
logger.info("Autowired annotation is not supported on static methods: " + method);
@@ -609,7 +608,7 @@ public class AutowiredAnnotationBeanPostProcessor implements SmartInstantiationA
}
}
boolean required = determineRequiredStatus(ann);
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
PropertyDescriptor pd = BeanUtils.findPropertyForMethod(method, clazz);
methodElements.add(new AutowiredMethodElement(method, required, pd));
}
});
@@ -180,7 +180,6 @@ public class QualifierAnnotationAutowireCandidateResolver extends GenericTypeAwa
* {@code true} if a qualifier has been found and matched,
* {@code null} if no qualifier has been found at all
*/
@Nullable
protected Boolean checkQualifiers(BeanDefinitionHolder bdHolder, Annotation[] annotationsToSearch) {
boolean qualifierFound = false;
@@ -375,6 +374,17 @@ public class QualifierAnnotationAutowireCandidateResolver extends GenericTypeAwa
return true;
}
}
MethodParameter methodParam = descriptor.getMethodParameter();
if (methodParam != null) {
Method method = methodParam.getMethod();
if (method == null || void.class == method.getReturnType()) {
for (Annotation annotation : methodParam.getMethodAnnotations()) {
if (isQualifier(annotation.annotationType())) {
return true;
}
}
}
}
return false;
}
@@ -29,6 +29,7 @@ import org.springframework.aot.generate.ValueCodeGenerator.Delegate;
import org.springframework.aot.generate.ValueCodeGeneratorDelegates;
import org.springframework.aot.generate.ValueCodeGeneratorDelegates.CollectionDelegate;
import org.springframework.aot.generate.ValueCodeGeneratorDelegates.MapDelegate;
import org.springframework.beans.factory.config.AutowiredPropertyMarker;
import org.springframework.beans.factory.config.BeanReference;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.config.TypedStringValue;
@@ -57,6 +58,7 @@ abstract class BeanDefinitionPropertyValueCodeGeneratorDelegates {
* <li>{@link LinkedHashMap}</li>
* <li>{@link BeanReference}</li>
* <li>{@link TypedStringValue}</li>
* <li>{@link AutowiredPropertyMarker}</li>
* </ul>
* When combined with {@linkplain ValueCodeGeneratorDelegates#INSTANCES the
* delegates for common value types}, this should be added first as they have
@@ -68,7 +70,8 @@ abstract class BeanDefinitionPropertyValueCodeGeneratorDelegates {
new ManagedMapDelegate(),
new LinkedHashMapDelegate(),
new BeanReferenceDelegate(),
new TypedStringValueDelegate()
new TypedStringValueDelegate(),
new AutowiredPropertyMarkerDelegate()
);
@@ -216,4 +219,20 @@ abstract class BeanDefinitionPropertyValueCodeGeneratorDelegates {
return valueCodeGenerator.generateCode(value);
}
}
/**
* {@link Delegate} for {@link AutowiredPropertyMarker} types.
*/
private static class AutowiredPropertyMarkerDelegate implements Delegate {
@Override
@Nullable
public CodeBlock generateCode(ValueCodeGenerator valueCodeGenerator, Object value) {
if (value instanceof AutowiredPropertyMarker) {
return CodeBlock.of("$T.INSTANCE", AutowiredPropertyMarker.class);
}
return null;
}
}
}
@@ -294,9 +294,12 @@ public class InstanceSupplierCodeGenerator {
this.generationContext.getRuntimeHints().reflection().registerMethod(factoryMethod, ExecutableMode.INVOKE);
GeneratedMethod getInstanceMethod = generateGetInstanceSupplierMethod(method -> {
CodeWarnings codeWarnings = new CodeWarnings();
Class<?> suppliedType = ClassUtils.resolvePrimitiveIfNecessary(factoryMethod.getReturnType());
codeWarnings.detectDeprecation(suppliedType, factoryMethod);
method.addJavadoc("Get the bean instance supplier for '$L'.", beanName);
method.addModifiers(PRIVATE_STATIC);
codeWarnings.suppress(method);
method.returns(ParameterizedTypeName.get(BeanInstanceSupplier.class, suppliedType));
method.addStatement(generateInstanceSupplierForFactoryMethod(
factoryMethod, suppliedType, targetClass, factoryMethod.getName()));
@@ -152,6 +152,18 @@ public interface ConfigurableListableBeanFactory
*/
boolean isConfigurationFrozen();
/**
* Mark current thread as main bootstrap thread for singleton instantiation,
* with lenient bootstrap locking applying for background threads.
* <p>Any such marker is to be removed at the end of the managed bootstrap in
* {@link #preInstantiateSingletons()}.
* @since 6.2.12
* @see #setBootstrapExecutor
* @see #preInstantiateSingletons()
*/
default void prepareSingletonBootstrap() {
}
/**
* Ensure that all non-lazy-init singletons are instantiated, also considering
* {@link org.springframework.beans.factory.FactoryBean FactoryBeans}.
@@ -159,6 +171,7 @@ public interface ConfigurableListableBeanFactory
* @throws BeansException if one of the singleton beans could not be created.
* Note: This may have left the factory with some beans already initialized!
* Call {@link #destroySingletons()} for full cleanup in this case.
* @see #prepareSingletonBootstrap()
* @see #destroySingletons()
*/
void preInstantiateSingletons() throws BeansException;
@@ -520,8 +520,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
* to check whether the bean with the given name matches the specified type. Allow
* additional constraints to be applied to ensure that beans are not created early.
* @param name the name of the bean to query
* @param typeToMatch the type to match against (as a
* {@code ResolvableType})
* @param typeToMatch the type to match against (as a {@code ResolvableType})
* @return {@code true} if the bean type matches, {@code false} if it
* doesn't match or cannot be determined yet
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
@@ -32,7 +32,6 @@ import org.springframework.util.StringUtils;
* @author Juergen Hoeller
* @author Rob Harrop
* @since 1.1
* @see PropertiesBeanDefinitionReader
* @see org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader
*/
public abstract class BeanDefinitionReaderUtils {
@@ -43,7 +43,6 @@ import org.springframework.core.AliasRegistry;
* @see DefaultListableBeanFactory
* @see org.springframework.context.support.GenericApplicationContext
* @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
* @see PropertiesBeanDefinitionReader
*/
public interface BeanDefinitionRegistry extends AliasRegistry {
@@ -58,6 +58,7 @@ import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
import org.springframework.beans.factory.CannotLoadBeanClassException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InjectionPoint;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
@@ -196,8 +197,8 @@ 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. */
private final Set<String> primaryBeanNames = ConcurrentHashMap.newKeySet(16);
/** Map of bean definition names with a primary marker plus corresponding type. */
private final Map<String, Class<?>> primaryBeanNamesWithType = new ConcurrentHashMap<>(16);
/** Map of singleton and non-singleton bean names, keyed by dependency type. */
private final Map<Class<?>, String[]> allBeanNamesByType = new ConcurrentHashMap<>(64);
@@ -1037,7 +1038,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
protected void cacheMergedBeanDefinition(RootBeanDefinition mbd, String beanName) {
super.cacheMergedBeanDefinition(mbd, beanName);
if (mbd.isPrimary()) {
this.primaryBeanNames.add(beanName);
this.primaryBeanNamesWithType.put(beanName, Void.class);
}
}
@@ -1101,6 +1102,11 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
return null;
}
@Override
public void prepareSingletonBootstrap() {
this.mainThreadPrefix = getThreadNamePrefix();
}
@Override
public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
@@ -1112,11 +1118,12 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
// Trigger initialization of all non-lazy singleton beans...
List<CompletableFuture<?>> futures = new ArrayList<>();
this.preInstantiationThread.set(PreInstantiation.MAIN);
this.mainThreadPrefix = getThreadNamePrefix();
if (this.mainThreadPrefix == null) {
this.mainThreadPrefix = getThreadNamePrefix();
}
try {
List<CompletableFuture<?>> futures = new ArrayList<>();
for (String beanName : beanNames) {
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
if (!mbd.isAbstract() && mbd.isSingleton()) {
@@ -1126,21 +1133,20 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
}
}
}
if (!futures.isEmpty()) {
try {
CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[0])).join();
}
catch (CompletionException ex) {
ReflectionUtils.rethrowRuntimeException(ex.getCause());
}
}
}
finally {
this.mainThreadPrefix = null;
this.preInstantiationThread.remove();
}
if (!futures.isEmpty()) {
try {
CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[0])).join();
}
catch (CompletionException ex) {
ReflectionUtils.rethrowRuntimeException(ex.getCause());
}
}
// Trigger post-initialization callback for all applicable beans...
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName, false);
@@ -1313,7 +1319,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
// Cache a primary marker for the given bean.
if (beanDefinition.isPrimary()) {
this.primaryBeanNames.add(beanName);
this.primaryBeanNamesWithType.put(beanName, Void.class);
}
}
@@ -1405,7 +1411,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
destroySingleton(beanName);
// Remove a cached primary marker for the given bean.
this.primaryBeanNames.remove(beanName);
this.primaryBeanNamesWithType.remove(beanName);
// Notify all post-processors that the specified bean definition has been reset.
for (MergedBeanDefinitionPostProcessor processor : getBeanPostProcessorCache().mergedDefinition) {
@@ -1455,11 +1461,30 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
}
}
@Override
protected void addSingleton(String beanName, Object singletonObject) {
super.addSingleton(beanName, singletonObject);
Predicate<Class<?>> filter = (beanType -> beanType != Object.class && beanType.isInstance(singletonObject));
this.allBeanNamesByType.keySet().removeIf(filter);
this.singletonBeanNamesByType.keySet().removeIf(filter);
if (this.primaryBeanNamesWithType.containsKey(beanName) && singletonObject.getClass() != NullBean.class) {
Class<?> beanType = (singletonObject instanceof FactoryBean<?> fb ?
getTypeForFactoryBean(fb) : singletonObject.getClass());
if (beanType != null) {
this.primaryBeanNamesWithType.put(beanName, beanType);
}
}
}
@Override
public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
super.registerSingleton(beanName, singletonObject);
updateManualSingletonNames(set -> set.add(beanName), set -> !this.beanDefinitionMap.containsKey(beanName));
clearByTypeCache();
this.allBeanNamesByType.remove(Object.class);
this.singletonBeanNamesByType.remove(Object.class);
}
@Override
@@ -1628,8 +1653,8 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
return doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
}
@SuppressWarnings("NullAway") // Dataflow analysis limitation
@Nullable
@SuppressWarnings("NullAway")
public Object doResolveDependency(DependencyDescriptor descriptor, @Nullable String beanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {
@@ -1966,7 +1991,8 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
DependencyDescriptor fallbackDescriptor = descriptor.forFallbackMatch();
for (String candidate : candidateNames) {
if (!isSelfReference(beanName, candidate) && isAutowireCandidate(candidate, fallbackDescriptor) &&
(!multiple || getAutowireCandidateResolver().hasQualifier(descriptor))) {
(!multiple || matchesBeanName(candidate, descriptor.getDependencyName()) ||
getAutowireCandidateResolver().hasQualifier(descriptor))) {
addCandidateEntry(result, candidate, descriptor, requiredType);
}
}
@@ -2083,8 +2109,9 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
boolean candidateLocal = containsBeanDefinition(candidateBeanName);
boolean primaryLocal = containsBeanDefinition(primaryBeanName);
if (candidateLocal == primaryLocal) {
throw new NoUniqueBeanDefinitionException(requiredType, candidates.size(),
"more than one 'primary' bean found among candidates: " + candidates.keySet());
String message = "more than one 'primary' bean found among candidates: " + candidates.keySet();
logger.trace(message);
throw new NoUniqueBeanDefinitionException(requiredType, candidates.size(), message);
}
else if (candidateLocal) {
primaryBeanName = candidateBeanName;
@@ -2236,12 +2263,12 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
}
/**
* Determine whether the given candidate name matches the bean name or the aliases
* Determine whether the given dependency name matches the bean name or the aliases
* stored in this bean definition.
*/
protected boolean matchesBeanName(String beanName, @Nullable String candidateName) {
return (candidateName != null &&
(candidateName.equals(beanName) || ObjectUtils.containsElement(getAliases(beanName), candidateName)));
protected boolean matchesBeanName(String beanName, @Nullable String dependencyName) {
return (dependencyName != null &&
(dependencyName.equals(beanName) || ObjectUtils.containsElement(getAliases(beanName), dependencyName)));
}
/**
@@ -2261,8 +2288,12 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
* not matching the given bean name.
*/
private boolean hasPrimaryConflict(String beanName, Class<?> dependencyType) {
for (String candidate : this.primaryBeanNames) {
if (isTypeMatch(candidate, dependencyType) && !candidate.equals(beanName)) {
for (Map.Entry<String, Class<?>> candidate : this.primaryBeanNamesWithType.entrySet()) {
String candidateName = candidate.getKey();
Class<?> candidateType = candidate.getValue();
if (!candidateName.equals(beanName) && (candidateType != Void.class ?
dependencyType.isAssignableFrom(candidateType) : // cached singleton class for primary bean
isTypeMatch(candidateName, dependencyType))) { // not instantiated yet or not a singleton
return true;
}
}
@@ -585,7 +585,7 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
public void registerContainedBean(String containedBeanName, String containingBeanName) {
synchronized (this.containedBeanMap) {
Set<String> containedBeans =
this.containedBeanMap.computeIfAbsent(containingBeanName, k -> new LinkedHashSet<>(8));
this.containedBeanMap.computeIfAbsent(containingBeanName, key -> new LinkedHashSet<>(8));
if (!containedBeans.add(containedBeanName)) {
return;
}
@@ -604,7 +604,7 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
synchronized (this.dependentBeanMap) {
Set<String> dependentBeans =
this.dependentBeanMap.computeIfAbsent(canonicalName, k -> new LinkedHashSet<>(8));
this.dependentBeanMap.computeIfAbsent(canonicalName, key -> new LinkedHashSet<>(8));
if (!dependentBeans.add(dependentBeanName)) {
return;
}
@@ -612,7 +612,7 @@ public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements
synchronized (this.dependenciesForBeanMap) {
Set<String> dependenciesForBean =
this.dependenciesForBeanMap.computeIfAbsent(dependentBeanName, k -> new LinkedHashSet<>(8));
this.dependenciesForBeanMap.computeIfAbsent(dependentBeanName, key -> new LinkedHashSet<>(8));
dependenciesForBean.add(canonicalName);
}
}
@@ -23,6 +23,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import org.apache.commons.logging.Log;
@@ -418,14 +419,29 @@ class DisposableBeanAdapter implements DisposableBean, Runnable, Serializable {
String destroyMethodName = beanDefinition.resolvedDestroyMethodName;
if (destroyMethodName == null) {
destroyMethodName = beanDefinition.getDestroyMethodName();
boolean autoCloseable = (AutoCloseable.class.isAssignableFrom(target));
boolean autoCloseable = AutoCloseable.class.isAssignableFrom(target);
boolean executorService = ExecutorService.class.isAssignableFrom(target);
if (AbstractBeanDefinition.INFER_METHOD.equals(destroyMethodName) ||
(destroyMethodName == null && autoCloseable)) {
(destroyMethodName == null && (autoCloseable || executorService))) {
// Only perform destroy method inference in case of the bean
// not explicitly implementing the DisposableBean interface
destroyMethodName = null;
if (!(DisposableBean.class.isAssignableFrom(target))) {
if (autoCloseable) {
if (executorService) {
destroyMethodName = SHUTDOWN_METHOD_NAME;
try {
// On JDK 19+, avoid the ExecutorService-level AutoCloseable default implementation
// which awaits task termination for 1 day, even for delayed tasks such as cron jobs.
// Custom close() implementations in ExecutorService subclasses are still accepted.
if (target.getMethod(CLOSE_METHOD_NAME).getDeclaringClass() != ExecutorService.class) {
destroyMethodName = CLOSE_METHOD_NAME;
}
}
catch (NoSuchMethodException ex) {
// Ignore - stick with shutdown()
}
}
else if (autoCloseable) {
destroyMethodName = CLOSE_METHOD_NAME;
}
else {
@@ -128,43 +128,48 @@ public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanReg
locked = (lockFlag && this.singletonLock.tryLock());
}
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 (locked) {
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 {
// Defensively synchronize against non-thread-safe FactoryBean.getObject() implementations,
// potentially to be called from a background thread while the main thread currently calls
// the same getObject() method within the singleton lock.
synchronized (factory) {
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 (locked) {
afterSingletonCreation(beanName);
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 {
if (locked) {
afterSingletonCreation(beanName);
}
}
}
}
if (containsSingleton(beanName)) {
this.factoryBeanObjectCache.put(beanName, object);
if (containsSingleton(beanName)) {
this.factoryBeanObjectCache.put(beanName, object);
}
}
}
return object;
}
return object;
}
finally {
if (locked) {
@@ -74,10 +74,10 @@ import org.springframework.util.StringUtils;
* @author Rob Harrop
* @since 26.11.2003
* @see DefaultListableBeanFactory
* @deprecated as of 5.3, in favor of Spring's common bean definition formats
* and/or custom reader implementations
* @deprecated in favor of Spring's common bean definition formats and/or
* custom BeanDefinitionReader implementations
*/
@Deprecated
@Deprecated(since = "5.3")
public class PropertiesBeanDefinitionReader extends AbstractBeanDefinitionReader {
/**
@@ -103,7 +103,7 @@ public class PathEditor extends PropertyEditorSupport {
if (resource == null) {
setValue(null);
}
else if (nioPathCandidate && !resource.exists()) {
else if (nioPathCandidate && (!resource.isFile() || !resource.exists())) {
setValue(Paths.get(text).normalize());
}
else {
@@ -472,7 +472,7 @@ abstract class AbstractPropertyAccessorTests {
assertThat(target.getAge()).as("age is OK").isEqualTo(age);
assertThat(name).as("name is OK").isEqualTo(target.getName());
accessor.setPropertyValues(new MutablePropertyValues());
// Check its unchanged
// Check it's unchanged
assertThat(target.getAge()).as("age is OK").isEqualTo(age);
assertThat(name).as("name is OK").isEqualTo(target.getName());
}
@@ -87,6 +87,7 @@ import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.core.testfixture.io.SerializationTestUtils;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.util.StringValueResolver;
import static org.assertj.core.api.Assertions.assertThat;
@@ -1798,7 +1799,7 @@ class DefaultListableBeanFactoryTests {
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class)
.isThrownBy(() -> lbf.getBean(TestBean.class))
.withMessageContaining("more than one 'primary'");
.withMessageEndingWith("more than one 'primary' bean found among candidates: [bd1, bd2]");
}
@Test
@@ -2122,7 +2123,7 @@ class DefaultListableBeanFactoryTests {
assertThatExceptionOfType(NoUniqueBeanDefinitionException.class)
.isThrownBy(() -> lbf.getBean(ConstructorDependency.class, 42))
.withMessageContaining("more than one 'primary'");
.withMessageEndingWith("more than one 'primary' bean found among candidates: [bd1, bd2]");
}
@Test
@@ -3202,6 +3203,33 @@ class DefaultListableBeanFactoryTests {
assertThat(holder.getNonPublicEnum()).isEqualTo(NonPublicEnum.VALUE_1);
}
@Test
void mostSpecificCacheEntryForTypeMatching() {
RootBeanDefinition bd1 = new RootBeanDefinition();
bd1.setFactoryBeanName("config");
bd1.setFactoryMethodName("create");
lbf.registerBeanDefinition("config", new RootBeanDefinition(BeanWithFactoryMethod.class));
lbf.registerBeanDefinition("bd1", bd1);
lbf.registerBeanDefinition("bd2", new RootBeanDefinition(NestedTestBean.class));
lbf.freezeConfiguration();
String[] allBeanNames = lbf.getBeanNamesForType(Object.class);
String[] nestedBeanNames = lbf.getBeanNamesForType(NestedTestBean.class);
assertThat(lbf.getType("bd1")).isEqualTo(TestBean.class);
assertThat(lbf.getBeanNamesForType(TestBean.class)).containsExactly("bd1");
assertThat(lbf.getBeanNamesForType(DerivedTestBean.class)).isEmpty();
lbf.getBean("bd1");
assertThat(lbf.getType("bd1")).isEqualTo(DerivedTestBean.class);
assertThat(lbf.getBeanNamesForType(TestBean.class)).containsExactly("bd1");
assertThat(lbf.getBeanNamesForType(DerivedTestBean.class)).containsExactly("bd1");
assertThat(lbf.getBeanNamesForType(NestedTestBean.class)).isSameAs(nestedBeanNames);
assertThat(lbf.getBeanNamesForType(Object.class)).isSameAs(allBeanNames);
lbf.registerSingleton("bd3", new Object());
assertThat(lbf.getBeanNamesForType(NestedTestBean.class)).isSameAs(nestedBeanNames);
assertThat(lbf.getBeanNamesForType(Object.class)).containsExactly(StringUtils.addStringToArray(allBeanNames, "bd3"));
}
private int registerBeanDefinitions(Properties p) {
return registerBeanDefinitions(p, null);
@@ -3418,7 +3446,7 @@ class DefaultListableBeanFactoryTests {
}
public TestBean create() {
TestBean tb = new TestBean();
DerivedTestBean tb = new DerivedTestBean();
tb.setName(this.name);
return tb;
}
@@ -3646,11 +3674,11 @@ class DefaultListableBeanFactoryTests {
private FactoryBean<?> factoryBean;
public final FactoryBean<?> getFactoryBean() {
public FactoryBean<?> getFactoryBean() {
return this.factoryBean;
}
public final void setFactoryBean(final FactoryBean<?> factoryBean) {
public void setFactoryBean(FactoryBean<?> factoryBean) {
this.factoryBean = factoryBean;
}
}
@@ -1275,88 +1275,6 @@ class AutowiredAnnotationBeanPostProcessorTests {
assertThat(bean.getTestBean().get("testBean2")).isNull();
}
@Test
void fieldInjectionWithMap() {
RootBeanDefinition bd = new RootBeanDefinition(MapFieldInjectionBean.class);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
TestBean tb1 = new TestBean("tb1");
TestBean tb2 = new TestBean("tb2");
bf.registerSingleton("testBean1", tb1);
bf.registerSingleton("testBean2", tb2);
bf.registerAlias("testBean1", "testBean");
MapFieldInjectionBean bean = bf.getBean("annotatedBean", MapFieldInjectionBean.class);
assertThat(bean.getTestBeanMap()).hasSize(2);
assertThat(bean.getTestBeanMap()).containsKey("testBean1");
assertThat(bean.getTestBeanMap()).containsKey("testBean2");
assertThat(bean.getTestBeanMap()).containsValue(tb1);
assertThat(bean.getTestBeanMap()).containsValue(tb2);
bean = bf.getBean("annotatedBean", MapFieldInjectionBean.class);
assertThat(bean.getTestBeanMap()).hasSize(2);
assertThat(bean.getTestBeanMap()).containsKey("testBean1");
assertThat(bean.getTestBeanMap()).containsKey("testBean2");
assertThat(bean.getTestBeanMap()).containsValue(tb1);
assertThat(bean.getTestBeanMap()).containsValue(tb2);
}
@Test
void methodInjectionWithMap() {
RootBeanDefinition bd = new RootBeanDefinition(MapMethodInjectionBean.class);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
TestBean tb = new TestBean();
bf.registerSingleton("testBean", tb);
MapMethodInjectionBean bean = bf.getBean("annotatedBean", MapMethodInjectionBean.class);
assertThat(bean.getTestBeanMap()).hasSize(1);
assertThat(bean.getTestBeanMap()).containsKey("testBean");
assertThat(bean.getTestBeanMap()).containsValue(tb);
assertThat(bean.getTestBean()).isSameAs(tb);
bean = bf.getBean("annotatedBean", MapMethodInjectionBean.class);
assertThat(bean.getTestBeanMap()).hasSize(1);
assertThat(bean.getTestBeanMap()).containsKey("testBean");
assertThat(bean.getTestBeanMap()).containsValue(tb);
assertThat(bean.getTestBean()).isSameAs(tb);
}
@Test
void methodInjectionWithMapAndMultipleMatches() {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(MapMethodInjectionBean.class));
bf.registerBeanDefinition("testBean1", new RootBeanDefinition(TestBean.class));
bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class));
assertThatExceptionOfType(UnsatisfiedDependencyException.class).as("should have failed, more than one bean of type")
.isThrownBy(() -> bf.getBean("annotatedBean"))
.satisfies(methodParameterDeclaredOn(MapMethodInjectionBean.class));
}
@Test
void methodInjectionWithMapAndMultipleMatchesButOnlyOneAutowireCandidate() {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(MapMethodInjectionBean.class));
bf.registerBeanDefinition("testBean1", new RootBeanDefinition(TestBean.class));
RootBeanDefinition rbd2 = new RootBeanDefinition(TestBean.class);
rbd2.setAutowireCandidate(false);
bf.registerBeanDefinition("testBean2", rbd2);
MapMethodInjectionBean bean = bf.getBean("annotatedBean", MapMethodInjectionBean.class);
TestBean tb = bf.getBean("testBean1", TestBean.class);
assertThat(bean.getTestBeanMap()).hasSize(1);
assertThat(bean.getTestBeanMap()).containsKey("testBean1");
assertThat(bean.getTestBeanMap()).containsValue(tb);
assertThat(bean.getTestBean()).isSameAs(tb);
}
@Test
void methodInjectionWithMapAndNoMatches() {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(MapMethodInjectionBean.class));
MapMethodInjectionBean bean = bf.getBean("annotatedBean", MapMethodInjectionBean.class);
assertThat(bean.getTestBeanMap()).isNull();
assertThat(bean.getTestBean()).isNull();
}
@Test
void constructorInjectionWithTypedMapAsBean() {
RootBeanDefinition bd = new RootBeanDefinition(MapConstructorInjectionBean.class);
@@ -1409,6 +1327,19 @@ class AutowiredAnnotationBeanPostProcessorTests {
@Test
void constructorInjectionWithPlainHashMapAsBean() {
RootBeanDefinition bd = new RootBeanDefinition(NamedMapConstructorInjectionBean.class);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
bf.registerBeanDefinition("testBeanMap", new RootBeanDefinition(HashMap.class));
NamedMapConstructorInjectionBean bean = bf.getBean("annotatedBean", NamedMapConstructorInjectionBean.class);
assertThat(bean.getTestBeanMap()).isSameAs(bf.getBean("testBeanMap"));
bean = bf.getBean("annotatedBean", NamedMapConstructorInjectionBean.class);
assertThat(bean.getTestBeanMap()).isSameAs(bf.getBean("testBeanMap"));
}
@Test
void constructorInjectionWithQualifiedPlainHashMapAsBean() {
RootBeanDefinition bd = new RootBeanDefinition(QualifiedMapConstructorInjectionBean.class);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
@@ -1497,6 +1428,114 @@ class AutowiredAnnotationBeanPostProcessorTests {
assertThat(bean.getTestBeanSet()).contains(tb1, tb2);
}
@Test
void fieldInjectionWithMap() {
RootBeanDefinition bd = new RootBeanDefinition(MapFieldInjectionBean.class);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
TestBean tb1 = new TestBean("tb1");
TestBean tb2 = new TestBean("tb2");
bf.registerSingleton("testBean1", tb1);
bf.registerSingleton("testBean2", tb2);
bf.registerAlias("testBean1", "testBean");
MapFieldInjectionBean bean = bf.getBean("annotatedBean", MapFieldInjectionBean.class);
assertThat(bean.getTestBeanMap()).hasSize(2);
assertThat(bean.getTestBeanMap()).containsKey("testBean1");
assertThat(bean.getTestBeanMap()).containsKey("testBean2");
assertThat(bean.getTestBeanMap()).containsValue(tb1);
assertThat(bean.getTestBeanMap()).containsValue(tb2);
bean = bf.getBean("annotatedBean", MapFieldInjectionBean.class);
assertThat(bean.getTestBeanMap()).hasSize(2);
assertThat(bean.getTestBeanMap()).containsKey("testBean1");
assertThat(bean.getTestBeanMap()).containsKey("testBean2");
assertThat(bean.getTestBeanMap()).containsValue(tb1);
assertThat(bean.getTestBeanMap()).containsValue(tb2);
}
@Test
void methodInjectionWithMap() {
RootBeanDefinition bd = new RootBeanDefinition(MapMethodInjectionBean.class);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
TestBean tb = new TestBean();
bf.registerSingleton("testBean", tb);
MapMethodInjectionBean bean = bf.getBean("annotatedBean", MapMethodInjectionBean.class);
assertThat(bean.getTestBeanMap()).hasSize(1);
assertThat(bean.getTestBeanMap()).containsKey("testBean");
assertThat(bean.getTestBeanMap()).containsValue(tb);
assertThat(bean.getTestBean()).isSameAs(tb);
bean = bf.getBean("annotatedBean", MapMethodInjectionBean.class);
assertThat(bean.getTestBeanMap()).hasSize(1);
assertThat(bean.getTestBeanMap()).containsKey("testBean");
assertThat(bean.getTestBeanMap()).containsValue(tb);
assertThat(bean.getTestBean()).isSameAs(tb);
}
@Test
void methodInjectionWithMapAndMultipleMatches() {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(MapMethodInjectionBean.class));
bf.registerBeanDefinition("testBean1", new RootBeanDefinition(TestBean.class));
bf.registerBeanDefinition("testBean2", new RootBeanDefinition(TestBean.class));
assertThatExceptionOfType(UnsatisfiedDependencyException.class).as("should have failed, more than one bean of type")
.isThrownBy(() -> bf.getBean("annotatedBean"))
.satisfies(methodParameterDeclaredOn(MapMethodInjectionBean.class));
}
@Test
void methodInjectionWithMapAndMultipleMatchesButOnlyOneAutowireCandidate() {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(MapMethodInjectionBean.class));
bf.registerBeanDefinition("testBean1", new RootBeanDefinition(TestBean.class));
RootBeanDefinition rbd2 = new RootBeanDefinition(TestBean.class);
rbd2.setAutowireCandidate(false);
bf.registerBeanDefinition("testBean2", rbd2);
MapMethodInjectionBean bean = bf.getBean("annotatedBean", MapMethodInjectionBean.class);
TestBean tb = bf.getBean("testBean1", TestBean.class);
assertThat(bean.getTestBeanMap()).hasSize(1);
assertThat(bean.getTestBeanMap()).containsKey("testBean1");
assertThat(bean.getTestBeanMap()).containsValue(tb);
assertThat(bean.getTestBean()).isSameAs(tb);
}
@Test
void methodInjectionWithMapAndNoMatches() {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(MapMethodInjectionBean.class));
MapMethodInjectionBean bean = bf.getBean("annotatedBean", MapMethodInjectionBean.class);
assertThat(bean.getTestBeanMap()).isNull();
assertThat(bean.getTestBean()).isNull();
}
@Test
void methodInjectionWithPlainHashMapAsBean() {
RootBeanDefinition bd = new RootBeanDefinition(NamedMapMethodInjectionBean.class);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
bf.registerBeanDefinition("testBeanMap", new RootBeanDefinition(HashMap.class));
NamedMapMethodInjectionBean bean = bf.getBean("annotatedBean", NamedMapMethodInjectionBean.class);
assertThat(bean.getTestBeanMap()).isSameAs(bf.getBean("testBeanMap"));
bean = bf.getBean("annotatedBean", NamedMapMethodInjectionBean.class);
assertThat(bean.getTestBeanMap()).isSameAs(bf.getBean("testBeanMap"));
}
@Test
void methodInjectionWithQualifiedPlainHashMapAsBean() {
RootBeanDefinition bd = new RootBeanDefinition(QualifiedMapMethodInjectionBean.class);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
bf.registerBeanDefinition("annotatedBean", bd);
bf.registerBeanDefinition("myTestBeanMap", new RootBeanDefinition(HashMap.class));
QualifiedMapMethodInjectionBean bean = bf.getBean("annotatedBean", QualifiedMapMethodInjectionBean.class);
assertThat(bean.getTestBeanMap()).isSameAs(bf.getBean("myTestBeanMap"));
bean = bf.getBean("annotatedBean", QualifiedMapMethodInjectionBean.class);
assertThat(bean.getTestBeanMap()).isSameAs(bf.getBean("myTestBeanMap"));
}
@Test
void selfReference() {
bf.registerBeanDefinition("annotatedBean", new RootBeanDefinition(SelfInjectionBean.class));
@@ -2073,8 +2112,8 @@ class AutowiredAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("factoryBeanDependentBean", new RootBeanDefinition(FactoryBeanDependentBean.class));
bf.registerSingleton("stringFactoryBean", new StringFactoryBean());
final StringFactoryBean factoryBean = (StringFactoryBean) bf.getBean("&stringFactoryBean");
final FactoryBeanDependentBean bean = (FactoryBeanDependentBean) bf.getBean("factoryBeanDependentBean");
StringFactoryBean factoryBean = (StringFactoryBean) bf.getBean("&stringFactoryBean");
FactoryBeanDependentBean bean = (FactoryBeanDependentBean) bf.getBean("factoryBeanDependentBean");
assertThat(factoryBean).as("The singleton StringFactoryBean should have been registered.").isNotNull();
assertThat(bean).as("The factoryBeanDependentBean should have been registered.").isNotNull();
@@ -2685,6 +2724,7 @@ class AutowiredAnnotationBeanPostProcessorTests {
bf.registerSingleton("nonNullBean", "Test");
bf.registerBeanDefinition("mixedNullableInjectionBean",
new RootBeanDefinition(MixedNullableInjectionBean.class));
MixedNullableInjectionBean mixedNullableInjectionBean = bf.getBean(MixedNullableInjectionBean.class);
assertThat(mixedNullableInjectionBean.nonNullBean).isNotNull();
assertThat(mixedNullableInjectionBean.nullableBean).isNull();
@@ -2695,6 +2735,7 @@ class AutowiredAnnotationBeanPostProcessorTests {
bf.registerSingleton("nonNullBean", "Test");
bf.registerBeanDefinition("mixedOptionalInjectionBean",
new RootBeanDefinition(MixedOptionalInjectionBean.class));
MixedOptionalInjectionBean mixedOptionalInjectionBean = bf.getBean(MixedOptionalInjectionBean.class);
assertThat(mixedOptionalInjectionBean.nonNullBean).isNotNull();
assertThat(mixedOptionalInjectionBean.nullableBean).isNull();
@@ -3258,6 +3299,21 @@ class AutowiredAnnotationBeanPostProcessorTests {
}
public static class NamedMapConstructorInjectionBean {
private Map<String, TestBean> testBeanMap;
@Autowired
public NamedMapConstructorInjectionBean(Map<String, TestBean> testBeanMap) {
this.testBeanMap = testBeanMap;
}
public Map<String, TestBean> getTestBeanMap() {
return this.testBeanMap;
}
}
public static class QualifiedMapConstructorInjectionBean {
private Map<String, TestBean> testBeanMap;
@@ -3357,6 +3413,37 @@ class AutowiredAnnotationBeanPostProcessorTests {
}
public static class NamedMapMethodInjectionBean {
private Map<String, TestBean> testBeanMap;
@Autowired
public void setTestBeanMap(Map<String, TestBean> testBeanMap) {
this.testBeanMap = testBeanMap;
}
public Map<String, TestBean> getTestBeanMap() {
return this.testBeanMap;
}
}
public static class QualifiedMapMethodInjectionBean {
private Map<String, TestBean> testBeanMap;
@Autowired
@Qualifier("myTestBeanMap")
public void setTestBeanMap(Map<String, TestBean> testBeanMap) {
this.testBeanMap = testBeanMap;
}
public Map<String, TestBean> getTestBeanMap() {
return this.testBeanMap;
}
}
@SuppressWarnings("serial")
public static class ObjectFactoryFieldInjectionBean implements Serializable {
@@ -444,8 +444,8 @@ class InjectAnnotationBeanPostProcessorTests {
bf.registerBeanDefinition("factoryBeanDependentBean", new RootBeanDefinition(FactoryBeanDependentBean.class));
bf.registerSingleton("stringFactoryBean", new StringFactoryBean());
final StringFactoryBean factoryBean = (StringFactoryBean) bf.getBean("&stringFactoryBean");
final FactoryBeanDependentBean bean = (FactoryBeanDependentBean) bf.getBean("factoryBeanDependentBean");
StringFactoryBean factoryBean = (StringFactoryBean) bf.getBean("&stringFactoryBean");
FactoryBeanDependentBean bean = (FactoryBeanDependentBean) bf.getBean("factoryBeanDependentBean");
assertThat(factoryBean).as("The singleton StringFactoryBean should have been registered.").isNotNull();
assertThat(bean).as("The factoryBeanDependentBean should have been registered.").isNotNull();
@@ -788,7 +788,6 @@ class InjectAnnotationBeanPostProcessorTests {
private ConfigurableListableBeanFactory beanFactory;
public ConstructorResourceInjectionBean() {
throw new UnsupportedOperationException();
}
@@ -16,6 +16,7 @@
package org.springframework.beans.factory.aot;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -34,6 +35,7 @@ import org.springframework.aot.generate.GenerationContext;
import org.springframework.aot.generate.MethodReference;
import org.springframework.aot.generate.MethodReference.ArgumentCodeGenerator;
import org.springframework.aot.test.generate.TestGenerationContext;
import org.springframework.beans.factory.config.AutowiredPropertyMarker;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConstructorArgumentValues.ValueHolder;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
@@ -626,6 +628,22 @@ class BeanDefinitionMethodGeneratorTests {
-> assertThat(customPropertyValue.value()).isEqualTo("test")));
}
@Test
void generateBeanDefinitionMethodWhenHasAutowiredPropertyGeneratesMethod() {
RootBeanDefinition beanDefinition = (RootBeanDefinition) BeanDefinitionBuilder
.rootBeanDefinition(CustomBean.class).addAutowiredProperty("innerBean")
.getBeanDefinition();
RegisteredBean registeredBean = registerBean(beanDefinition);
BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator(
this.methodGeneratorFactory, registeredBean, null,
Collections.emptyList());
MethodReference method = generator.generateBeanDefinitionMethod(
this.generationContext, this.beanRegistrationsCode);
compile(method, (actual, compiled) ->
assertThat(actual.getPropertyValues().get("innerBean"))
.isSameAs(AutowiredPropertyMarker.INSTANCE));
}
@Test
void generateBeanDefinitionMethodWhenHasAotContributionsAppliesContributions() {
RegisteredBean registeredBean = registerBean(
@@ -39,6 +39,7 @@ import org.springframework.aot.generate.GeneratedClass;
import org.springframework.aot.generate.ValueCodeGenerator;
import org.springframework.aot.generate.ValueCodeGeneratorDelegates;
import org.springframework.aot.test.generate.TestGenerationContext;
import org.springframework.beans.factory.config.AutowiredPropertyMarker;
import org.springframework.beans.factory.config.BeanReference;
import org.springframework.beans.factory.config.RuntimeBeanNameReference;
import org.springframework.beans.factory.config.RuntimeBeanReference;
@@ -486,4 +487,16 @@ class BeanDefinitionPropertyValueCodeGeneratorDelegatesTests {
}
@Nested
class AutowiredPropertyMarkerTests {
@Test
void generateWhenAutowiredPropertyMarker() {
compile(AutowiredPropertyMarker.INSTANCE, (instance, compiler) ->
assertThat(instance).isInstanceOf(AutowiredPropertyMarker.class)
.isSameAs(AutowiredPropertyMarker.INSTANCE));
}
}
}
@@ -418,6 +418,16 @@ class InstanceSupplierCodeGeneratorTests {
compileAndCheckWarnings(beanDefinition);
}
@Test
void generateWhenTargetFactoryMethodIsProtectedAndReturnTypeIsDeprecated() {
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(DeprecatedBean.class)
.setFactoryMethodOnBean("deprecatedReturnTypeProtected", "config").getBeanDefinition();
beanFactory.registerBeanDefinition("config", BeanDefinitionBuilder
.genericBeanDefinition(DeprecatedMemberConfiguration.class).getBeanDefinition());
compileAndCheckWarnings(beanDefinition);
}
private void compileAndCheckWarnings(BeanDefinition beanDefinition) {
assertThatNoException().isThrownBy(() -> compile(TEST_COMPILER, beanDefinition,
((instanceSupplier, compiled) -> {})));
@@ -464,6 +474,26 @@ class InstanceSupplierCodeGeneratorTests {
compileAndCheckWarnings(beanDefinition);
}
@Test
void generateWhenTargetFactoryMethodReturnTypeIsDeprecatedForRemoval() {
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(DeprecatedForRemovalBean.class)
.setFactoryMethodOnBean("deprecatedReturnType", "config").getBeanDefinition();
beanFactory.registerBeanDefinition("config", BeanDefinitionBuilder
.genericBeanDefinition(DeprecatedForRemovalMemberConfiguration.class).getBeanDefinition());
compileAndCheckWarnings(beanDefinition);
}
@Test
void generateWhenTargetFactoryMethodIsProtectedAndReturnTypeIsDeprecatedForRemoval() {
BeanDefinition beanDefinition = BeanDefinitionBuilder
.rootBeanDefinition(DeprecatedForRemovalBean.class)
.setFactoryMethodOnBean("deprecatedReturnTypeProtected", "config").getBeanDefinition();
beanFactory.registerBeanDefinition("config", BeanDefinitionBuilder
.genericBeanDefinition(DeprecatedForRemovalMemberConfiguration.class).getBeanDefinition());
compileAndCheckWarnings(beanDefinition);
}
private void compileAndCheckWarnings(BeanDefinition beanDefinition) {
assertThatNoException().isThrownBy(() -> compile(TEST_COMPILER, beanDefinition,
((instanceSupplier, compiled) -> {})));
@@ -17,6 +17,7 @@
package org.springframework.beans.factory.support;
import java.lang.reflect.Method;
import java.util.concurrent.ExecutorService;
import org.junit.jupiter.api.Test;
@@ -59,13 +60,38 @@ class RootBeanDefinitionTests {
}
@Test
void resolveDestroyMethodWithMatchingCandidateReplacedInferredVaue() {
void resolveDestroyMethodWithMatchingCandidateReplacedForCloseMethod() {
RootBeanDefinition beanDefinition = new RootBeanDefinition(BeanWithCloseMethod.class);
beanDefinition.setDestroyMethodName(AbstractBeanDefinition.INFER_METHOD);
beanDefinition.resolveDestroyMethodIfNecessary();
assertThat(beanDefinition.getDestroyMethodNames()).containsExactly("close");
}
@Test
void resolveDestroyMethodWithMatchingCandidateReplacedForShutdownMethod() {
RootBeanDefinition beanDefinition = new RootBeanDefinition(BeanWithShutdownMethod.class);
beanDefinition.setDestroyMethodName(AbstractBeanDefinition.INFER_METHOD);
beanDefinition.resolveDestroyMethodIfNecessary();
assertThat(beanDefinition.getDestroyMethodNames()).containsExactly("shutdown");
}
@Test
void resolveDestroyMethodWithMatchingCandidateReplacedForExecutorService() {
RootBeanDefinition beanDefinition = new RootBeanDefinition(BeanImplementingExecutorService.class);
beanDefinition.setDestroyMethodName(AbstractBeanDefinition.INFER_METHOD);
beanDefinition.resolveDestroyMethodIfNecessary();
assertThat(beanDefinition.getDestroyMethodNames()).containsExactly("shutdown");
// even on JDK 19+ where the ExecutorService interface declares a default AutoCloseable implementation
}
@Test
void resolveDestroyMethodWithMatchingCandidateReplacedForAutoCloseableExecutorService() {
RootBeanDefinition beanDefinition = new RootBeanDefinition(BeanImplementingExecutorServiceAndAutoCloseable.class);
beanDefinition.setDestroyMethodName(AbstractBeanDefinition.INFER_METHOD);
beanDefinition.resolveDestroyMethodIfNecessary();
assertThat(beanDefinition.getDestroyMethodNames()).containsExactly("close");
}
@Test
void resolveDestroyMethodWithNoCandidateSetDestroyMethodNameToNull() {
RootBeanDefinition beanDefinition = new RootBeanDefinition(BeanWithNoDestroyMethod.class);
@@ -90,6 +116,25 @@ class RootBeanDefinitionTests {
}
static class BeanWithShutdownMethod {
public void shutdown() {
}
}
abstract static class BeanImplementingExecutorService implements ExecutorService {
}
abstract static class BeanImplementingExecutorServiceAndAutoCloseable implements ExecutorService, AutoCloseable {
@Override
public void close() {
}
}
static class BeanWithNoDestroyMethod {
}
@@ -28,6 +28,7 @@ import org.assertj.core.api.InstanceOfAssertFactories;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.beans.factory.config.FieldRetrievingFactoryBean;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.beans.factory.parsing.ComponentDefinition;
@@ -46,7 +47,6 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Juergen Hoeller
* @author Mark Fisher
*/
@SuppressWarnings("rawtypes")
class UtilNamespaceHandlerTests {
private DefaultListableBeanFactory beanFactory;
@@ -55,7 +55,7 @@ class UtilNamespaceHandlerTests {
@BeforeEach
void setUp() {
void setup() {
this.beanFactory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.beanFactory);
reader.setEventListener(this.listener);
@@ -109,17 +109,17 @@ class UtilNamespaceHandlerTests {
@Test
void testSimpleMap() {
Map<?, ?> map = (Map) this.beanFactory.getBean("simpleMap");
Map<?, ?> map = (Map<?, ?>) this.beanFactory.getBean("simpleMap");
assertThat(map.get("foo")).isEqualTo("bar");
Map<?, ?> map2 = (Map) this.beanFactory.getBean("simpleMap");
Map<?, ?> map2 = (Map<?, ?>) this.beanFactory.getBean("simpleMap");
assertThat(map).isSameAs(map2);
}
@Test
void testScopedMap() {
Map<?, ?> map = (Map) this.beanFactory.getBean("scopedMap");
Map<?, ?> map = (Map<?, ?>) this.beanFactory.getBean("scopedMap");
assertThat(map.get("foo")).isEqualTo("bar");
Map<?, ?> map2 = (Map) this.beanFactory.getBean("scopedMap");
Map<?, ?> map2 = (Map<?, ?>) this.beanFactory.getBean("scopedMap");
assertThat(map2.get("foo")).isEqualTo("bar");
assertThat(map).isNotSameAs(map2);
}
@@ -164,17 +164,23 @@ class UtilNamespaceHandlerTests {
}
@Test
void testMapWithRef() {
Map<?, ?> map = (Map) this.beanFactory.getBean("mapWithRef");
void testMapWithRef() throws Exception {
Map<?, ?> map = (Map<?, ?>) this.beanFactory.getBean("mapWithRef");
assertThat(map).isInstanceOf(TreeMap.class);
assertThat(map.get("bean")).isEqualTo(this.beanFactory.getBean("testBean"));
assertThat(this.beanFactory.resolveDependency(
new DependencyDescriptor(getClass().getDeclaredField("mapWithRef"), true), null))
.isSameAs(map);
}
@Test
void testMapWithTypes() {
Map<?, ?> map = (Map) this.beanFactory.getBean("mapWithTypes");
void testMapWithTypes() throws Exception {
Map<?, ?> map = (Map<?, ?>) this.beanFactory.getBean("mapWithTypes");
assertThat(map).isInstanceOf(LinkedCaseInsensitiveMap.class);
assertThat(map.get("bean")).isEqualTo(this.beanFactory.getBean("testBean"));
assertThat(this.beanFactory.resolveDependency(
new DependencyDescriptor(getClass().getDeclaredField("mapWithTypes"), true), null))
.isSameAs(map);
}
@Test
@@ -240,11 +246,11 @@ class UtilNamespaceHandlerTests {
void testCircularCollections() {
TestBean bean = (TestBean) this.beanFactory.getBean("circularCollectionsBean");
assertThat(bean.getSomeList()).singleElement().isEqualTo(bean);
assertThat(bean.getSomeSet()).singleElement().isEqualTo(bean);
assertThat(bean.getSomeList()).singleElement().isSameAs(bean);
assertThat(bean.getSomeSet()).singleElement().isSameAs(bean);
assertThat(bean.getSomeMap()).hasSize(1).allSatisfy((key, value) -> {
assertThat(key).isEqualTo("foo");
assertThat(value).isEqualTo(bean);
assertThat(value).isSameAs(bean);
});
}
@@ -255,17 +261,17 @@ class UtilNamespaceHandlerTests {
List<?> list = bean.getSomeList();
assertThat(Proxy.isProxyClass(list.getClass())).isTrue();
assertThat(list).singleElement().isEqualTo(bean);
assertThat(list).singleElement().isSameAs(bean);
Set<?> set = bean.getSomeSet();
assertThat(Proxy.isProxyClass(set.getClass())).isFalse();
assertThat(set).singleElement().isEqualTo(bean);
assertThat(set).singleElement().isSameAs(bean);
Map<?, ?> map = bean.getSomeMap();
assertThat(Proxy.isProxyClass(map.getClass())).isFalse();
assertThat(map).hasSize(1).allSatisfy((key, value) -> {
assertThat(key).isEqualTo("foo");
assertThat(value).isEqualTo(bean);
assertThat(value).isSameAs(bean);
});
}
@@ -276,17 +282,17 @@ class UtilNamespaceHandlerTests {
List<?> list = bean.getSomeList();
assertThat(Proxy.isProxyClass(list.getClass())).isFalse();
assertThat(list).singleElement().isEqualTo(bean);
assertThat(list).singleElement().isSameAs(bean);
Set<?> set = bean.getSomeSet();
assertThat(Proxy.isProxyClass(set.getClass())).isTrue();
assertThat(set).singleElement().isEqualTo(bean);
assertThat(set).singleElement().isSameAs(bean);
Map<?, ?> map = bean.getSomeMap();
assertThat(Proxy.isProxyClass(map.getClass())).isFalse();
assertThat(map).hasSize(1).allSatisfy((key, value) -> {
assertThat(key).isEqualTo("foo");
assertThat(value).isEqualTo(bean);
assertThat(value).isSameAs(bean);
});
}
@@ -297,17 +303,17 @@ class UtilNamespaceHandlerTests {
List<?> list = bean.getSomeList();
assertThat(Proxy.isProxyClass(list.getClass())).isFalse();
assertThat(list).singleElement().isEqualTo(bean);
assertThat(list).singleElement().isSameAs(bean);
Set<?> set = bean.getSomeSet();
assertThat(Proxy.isProxyClass(set.getClass())).isFalse();
assertThat(set).singleElement().isEqualTo(bean);
assertThat(set).singleElement().isSameAs(bean);
Map<?, ?> map = bean.getSomeMap();
assertThat(Proxy.isProxyClass(map.getClass())).isTrue();
assertThat(map).hasSize(1).allSatisfy((key, value) -> {
assertThat(key).isEqualTo("foo");
assertThat(value).isEqualTo(bean);
assertThat(value).isSameAs(bean);
});
}
@@ -372,4 +378,9 @@ class UtilNamespaceHandlerTests {
assertThat(props).as("Incorrect property value").containsEntry("foo2", "local2");
}
// For DependencyDescriptor resolution
private Map<String, TestBean> mapWithRef;
private Map<String, TestBean> mapWithTypes;
}
@@ -59,6 +59,8 @@ public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOt
private boolean jedi;
private String favoriteCafé;
private ITestBean spouse;
private String touchy;
@@ -209,6 +211,14 @@ public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOt
this.jedi = jedi;
}
public String getFavoriteCafé() {
return this.favoriteCafé;
}
public void setFavoriteCafé(String favoriteCafé) {
this.favoriteCafé = favoriteCafé;
}
@Override
public ITestBean getSpouse() {
return this.spouse;
@@ -33,4 +33,14 @@ public class DeprecatedForRemovalMemberConfiguration {
return bean.toString();
}
@SuppressWarnings("removal")
public DeprecatedForRemovalBean deprecatedReturnType() {
return new DeprecatedForRemovalBean();
}
@SuppressWarnings("removal")
DeprecatedForRemovalBean deprecatedReturnTypeProtected() {
return new DeprecatedForRemovalBean();
}
}
@@ -38,4 +38,9 @@ public class DeprecatedMemberConfiguration {
return new DeprecatedBean();
}
@SuppressWarnings("deprecation")
DeprecatedBean deprecatedReturnTypeProtected() {
return new DeprecatedBean();
}
}
@@ -37,12 +37,13 @@ import javax.lang.model.element.TypeElement;
/**
* Annotation {@link Processor} that writes a {@link CandidateComponentsMetadata}
* file for spring components.
* file for Spring components.
*
* @author Stephane Nicoll
* @author Juergen Hoeller
* @since 5.0
* @deprecated as of 6.1, in favor of the AOT engine.
* @deprecated as of 6.1, in favor of the AOT engine and the forthcoming
* support for an AOT-generated Spring components index
*/
@Deprecated(since = "6.1", forRemoval = true)
public class CandidateComponentsIndexer implements Processor {
@@ -25,8 +25,8 @@ import javax.lang.model.element.ElementKind;
/**
* A {@link StereotypesProvider} that extracts a stereotype for each
* {@code jakarta.*} or {@code javax.*} annotation <i>present</i> on a class or
* interface.
* {@code jakarta.*} or {@code javax.*} annotation <i>present</i>
* on a class or interface.
*
* @author Stephane Nicoll
* @since 5.0
@@ -77,7 +77,7 @@ public class CaffeineCacheManager implements CacheManager {
private boolean allowNullValues = true;
private boolean dynamic = true;
private volatile boolean dynamic = true;
private final Map<String, Cache> cacheMap = new ConcurrentHashMap<>(16);
@@ -102,10 +102,15 @@ public class CaffeineCacheManager implements CacheManager {
/**
* Specify the set of cache names for this CacheManager's 'static' mode.
* <p>The number of caches and their names will be fixed after a call to this method,
* with no creation of further cache regions at runtime.
* <p>Calling this with a {@code null} collection argument resets the
* mode to 'dynamic', allowing for further creation of caches again.
* <p>The number of caches and their names will be fixed after a call
* to this method, with no creation of further cache regions at runtime.
* <p>Note that this method replaces existing caches of the given names
* and prevents the creation of further cache regions from here on - but
* does <i>not</i> remove unrelated existing caches. For a full reset,
* consider calling {@link #resetCaches()} before calling this method.
* <p>Calling this method with a {@code null} collection argument resets
* the mode to 'dynamic', allowing for further creation of caches again.
* @see #resetCaches()
*/
public void setCacheNames(@Nullable Collection<String> cacheNames) {
if (cacheNames != null) {
@@ -245,11 +250,6 @@ public class CaffeineCacheManager implements CacheManager {
}
@Override
public Collection<String> getCacheNames() {
return Collections.unmodifiableSet(this.cacheMap.keySet());
}
@Override
@Nullable
public Cache getCache(String name) {
@@ -260,6 +260,33 @@ public class CaffeineCacheManager implements CacheManager {
return cache;
}
@Override
public Collection<String> getCacheNames() {
return Collections.unmodifiableSet(this.cacheMap.keySet());
}
/**
* Reset this cache manager's caches, removing them completely for on-demand
* re-creation in 'dynamic' mode, or simply clearing their entries otherwise.
* @since 6.2.14
*/
public void resetCaches() {
this.cacheMap.values().forEach(Cache::clear);
if (this.dynamic) {
this.cacheMap.keySet().retainAll(this.customCacheNames);
}
}
/**
* Remove the specified cache from this cache manager, applying to
* custom caches as well as dynamically registered caches at runtime.
* @param name the name of the cache
* @since 6.1.15
*/
public void removeCache(String name) {
this.customCacheNames.remove(name);
this.cacheMap.remove(name);
}
/**
* Register the given native Caffeine Cache instance with this cache manager,
@@ -303,16 +330,6 @@ public class CaffeineCacheManager implements CacheManager {
this.cacheMap.put(name, adaptCaffeineCache(name, cache));
}
/**
* Remove the specified cache from this cache manager, applying to
* custom caches as well as dynamically registered caches at runtime.
* @param name the name of the cache
* @since 6.1.15
*/
public void removeCache(String name) {
this.customCacheNames.remove(name);
this.cacheMap.remove(name);
}
/**
* Adapt the given new native Caffeine Cache instance to Spring's {@link Cache}
@@ -25,6 +25,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.core.MethodClassKey;
import org.springframework.lang.Nullable;
import org.springframework.util.ReflectionUtils;
@@ -97,6 +98,10 @@ public abstract class AbstractFallbackJCacheOperationSource implements JCacheOpe
if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
return null;
}
// Skip setBeanFactory method on BeanFactoryAware.
if (method.getDeclaringClass() == BeanFactoryAware.class) {
return null;
}
// The method may be on an interface, but we need metadata from the target class.
// If the target class is null, the method will be unchanged.
@@ -24,7 +24,6 @@ import com.github.benmanes.caffeine.cache.CaffeineSpec;
import org.junit.jupiter.api.Test;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.support.SimpleValueWrapper;
import static org.assertj.core.api.Assertions.assertThat;
@@ -42,7 +41,7 @@ class CaffeineCacheManagerTests {
@Test
@SuppressWarnings("cast")
void dynamicMode() {
CacheManager cm = new CaffeineCacheManager();
CaffeineCacheManager cm = new CaffeineCacheManager();
Cache cache1 = cm.getCache("c1");
assertThat(cache1).isInstanceOf(CaffeineCache.class);
@@ -76,6 +75,14 @@ class CaffeineCacheManagerTests {
cache1.evict("key3");
assertThat(cache1.get("key3", () -> (String) null)).isNull();
assertThat(cache1.get("key3", () -> (String) null)).isNull();
cm.removeCache("c1");
assertThat(cm.getCache("c1")).isNotSameAs(cache1);
assertThat(cm.getCache("c2")).isSameAs(cache2);
cm.resetCaches();
assertThat(cm.getCache("c1")).isNotSameAs(cache1);
assertThat(cm.getCache("c2")).isNotSameAs(cache2);
}
@Test
@@ -131,11 +138,24 @@ class CaffeineCacheManagerTests {
cm.setAllowNullValues(true);
Cache cache1y = cm.getCache("c1");
Cache cache2y = cm.getCache("c2");
cache1y.put("key3", null);
assertThat(cache1y.get("key3").get()).isNull();
cache1y.evict("key3");
assertThat(cache1y.get("key3")).isNull();
cache2y.put("key4", "value4");
assertThat(cache2y.get("key4").get()).isEqualTo("value4");
cm.removeCache("c1");
assertThat(cm.getCache("c1")).isNull();
assertThat(cm.getCache("c2")).isSameAs(cache2y);
assertThat(cache2y.get("key4").get()).isEqualTo("value4");
cm.resetCaches();
assertThat(cm.getCache("c1")).isNull();
assertThat(cm.getCache("c2")).isSameAs(cache2y);
assertThat(cache2y.get("key4")).isNull();
}
@Test
@@ -51,8 +51,7 @@ class JCacheEhCacheApiTests extends AbstractValueAdaptingCacheTests<JCacheCache>
this.cacheManager.createCache(CACHE_NAME_NO_NULL, new MutableConfiguration<>());
this.nativeCache = this.cacheManager.getCache(CACHE_NAME);
this.cache = new JCacheCache(this.nativeCache);
Cache<Object, Object> nativeCacheNoNull =
this.cacheManager.getCache(CACHE_NAME_NO_NULL);
Cache<Object, Object> nativeCacheNoNull = this.cacheManager.getCache(CACHE_NAME_NO_NULL);
this.cacheNoNull = new JCacheCache(nativeCacheNoNull, false);
}
@@ -23,14 +23,14 @@ import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.lang.Nullable;
/**
* Interface to be implemented by @{@link org.springframework.context.annotation.Configuration
* Configuration} classes annotated with @{@link EnableCaching} that wish or need to specify
* explicitly how caches are resolved and how keys are generated for annotation-driven
* cache management.
* Interface to be implemented for explicitly specifying how caches are resolved
* and how keys are generated for annotation-driven cache management.
*
* <p>See @{@link EnableCaching} for general examples and context; see
* {@link #cacheManager()}, {@link #cacheResolver()}, {@link #keyGenerator()}, and
* {@link #errorHandler()} for detailed instructions.
* <p>Typically implemented by @{@link org.springframework.context.annotation.Configuration
* Configuration} classes annotated with @{@link EnableCaching}.
* See @{@link EnableCaching} for general examples and context; see
* {@link #cacheManager()}, {@link #cacheResolver()}, {@link #keyGenerator()},
* and {@link #errorHandler()} for detailed instructions.
*
* <p><b>NOTE: A {@code CachingConfigurer} will get initialized early.</b>
* Do not inject common dependencies into autowired fields directly; instead, consider
@@ -54,7 +54,7 @@ public class ConcurrentMapCacheManager implements CacheManager, BeanClassLoaderA
private final ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<>(16);
private boolean dynamic = true;
private volatile boolean dynamic = true;
private boolean allowNullValues = true;
@@ -82,10 +82,15 @@ public class ConcurrentMapCacheManager implements CacheManager, BeanClassLoaderA
/**
* Specify the set of cache names for this CacheManager's 'static' mode.
* <p>The number of caches and their names will be fixed after a call to this method,
* with no creation of further cache regions at runtime.
* <p>Calling this with a {@code null} collection argument resets the
* mode to 'dynamic', allowing for further creation of caches again.
* <p>The number of caches and their names will be fixed after a call
* to this method, with no creation of further cache regions at runtime.
* <p>Note that this method replaces existing caches of the given names
* and prevents the creation of further cache regions from here on - but
* does <i>not</i> remove unrelated existing caches. For a full reset,
* consider calling {@link #resetCaches()} before calling this method.
* <p>Calling this method with a {@code null} collection argument resets
* the mode to 'dynamic', allowing for further creation of caches again.
* @see #resetCaches()
*/
public void setCacheNames(@Nullable Collection<String> cacheNames) {
if (cacheNames != null) {
@@ -160,11 +165,6 @@ public class ConcurrentMapCacheManager implements CacheManager, BeanClassLoaderA
}
@Override
public Collection<String> getCacheNames() {
return Collections.unmodifiableSet(this.cacheMap.keySet());
}
@Override
@Nullable
public Cache getCache(String name) {
@@ -175,6 +175,23 @@ public class ConcurrentMapCacheManager implements CacheManager, BeanClassLoaderA
return cache;
}
@Override
public Collection<String> getCacheNames() {
return Collections.unmodifiableSet(this.cacheMap.keySet());
}
/**
* Reset this cache manager's caches, removing them completely for on-demand
* re-creation in 'dynamic' mode, or simply clearing their entries otherwise.
* @since 6.2.14
*/
public void resetCaches() {
this.cacheMap.values().forEach(Cache::clear);
if (this.dynamic) {
this.cacheMap.clear();
}
}
/**
* Remove the specified cache from this cache manager.
* @param name the name of the cache
@@ -113,7 +113,7 @@ class CacheAdviceParser extends AbstractSingleBeanDefinitionParser {
builder.setUnless(getAttributeValue(opElement, "unless", ""));
builder.setSync(Boolean.parseBoolean(getAttributeValue(opElement, "sync", "false")));
Collection<CacheOperation> col = cacheOpMap.computeIfAbsent(nameHolder, k -> new ArrayList<>(2));
Collection<CacheOperation> col = cacheOpMap.computeIfAbsent(nameHolder, key -> new ArrayList<>(2));
col.add(builder.build());
}
@@ -136,7 +136,7 @@ class CacheAdviceParser extends AbstractSingleBeanDefinitionParser {
builder.setBeforeInvocation(Boolean.parseBoolean(after.trim()));
}
Collection<CacheOperation> col = cacheOpMap.computeIfAbsent(nameHolder, k -> new ArrayList<>(2));
Collection<CacheOperation> col = cacheOpMap.computeIfAbsent(nameHolder, key -> new ArrayList<>(2));
col.add(builder.build());
}
@@ -150,7 +150,7 @@ class CacheAdviceParser extends AbstractSingleBeanDefinitionParser {
parserContext.getReaderContext(), new CachePutOperation.Builder());
builder.setUnless(getAttributeValue(opElement, "unless", ""));
Collection<CacheOperation> col = cacheOpMap.computeIfAbsent(nameHolder, k -> new ArrayList<>(2));
Collection<CacheOperation> col = cacheOpMap.computeIfAbsent(nameHolder, key -> new ArrayList<>(2));
col.add(builder.build());
}
@@ -27,6 +27,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.core.MethodClassKey;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
@@ -139,6 +140,10 @@ public abstract class AbstractFallbackCacheOperationSource implements CacheOpera
if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
return null;
}
// Skip setBeanFactory method on BeanFactoryAware.
if (method.getDeclaringClass() == BeanFactoryAware.class) {
return null;
}
// The method may be on an interface, but we need metadata from the target class.
// If the target class is null, the method will be unchanged.
@@ -18,8 +18,6 @@ package org.springframework.cache.support;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@@ -32,45 +30,29 @@ import org.springframework.lang.Nullable;
* for disabling caching, typically used for backing cache declarations
* without an actual backing store.
*
* <p>Will simply accept any items into the cache not actually storing them.
* <p>This implementation will simply accept any items into the cache,
* not actually storing them.
*
* @author Costin Leau
* @author Stephane Nicoll
* @author Juergen Hoeller
* @since 3.1
* @see NoOpCache
*/
public class NoOpCacheManager implements CacheManager {
private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<>(16);
private final Set<String> cacheNames = new LinkedHashSet<>(16);
private final ConcurrentMap<String, Cache> cacheMap = new ConcurrentHashMap<>(16);
/**
* This implementation always returns a {@link Cache} implementation that will not store items.
* Additionally, the request cache will be remembered by the manager for consistency.
*/
@Override
@Nullable
public Cache getCache(String name) {
Cache cache = this.caches.get(name);
if (cache == null) {
this.caches.computeIfAbsent(name, NoOpCache::new);
synchronized (this.cacheNames) {
this.cacheNames.add(name);
}
}
return this.caches.get(name);
return this.cacheMap.computeIfAbsent(name, NoOpCache::new);
}
/**
* This implementation returns the name of the caches previously requested.
*/
@Override
public Collection<String> getCacheNames() {
synchronized (this.cacheNames) {
return Collections.unmodifiableSet(this.cacheNames);
}
return Collections.unmodifiableSet(this.cacheMap.keySet());
}
}
@@ -55,7 +55,7 @@ public interface MessageSource {
* @see java.text.MessageFormat
*/
@Nullable
String getMessage(String code, @Nullable Object[] args, @Nullable String defaultMessage, Locale locale);
String getMessage(String code, @Nullable Object[] args, @Nullable String defaultMessage, @Nullable Locale locale);
/**
* Try to resolve the message. Treat as an error if the message can't be found.
@@ -71,7 +71,7 @@ public interface MessageSource {
* @see #getMessage(MessageSourceResolvable, Locale)
* @see java.text.MessageFormat
*/
String getMessage(String code, @Nullable Object[] args, Locale locale) throws NoSuchMessageException;
String getMessage(String code, @Nullable Object[] args, @Nullable Locale locale) throws NoSuchMessageException;
/**
* Try to resolve the message using all the attributes contained within the
@@ -91,6 +91,6 @@ public interface MessageSource {
* @see MessageSourceResolvable#getDefaultMessage()
* @see java.text.MessageFormat
*/
String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException;
String getMessage(MessageSourceResolvable resolvable, @Nullable Locale locale) throws NoSuchMessageException;
}
@@ -17,19 +17,18 @@
package org.springframework.context.annotation;
/**
* Enumeration used to determine whether JDK proxy-based or
* Enumeration used to determine whether JDK/CGLIB proxy-based or
* AspectJ weaving-based advice should be applied.
*
* @author Chris Beams
* @since 3.1
* @see org.springframework.scheduling.annotation.EnableAsync#mode()
* @see org.springframework.scheduling.annotation.AsyncConfigurationSelector#selectImports
* @see org.springframework.transaction.annotation.EnableTransactionManagement#mode()
* @see org.springframework.scheduling.annotation.EnableAsync#mode()
*/
public enum AdviceMode {
/**
* JDK proxy-based advice.
* JDK/CGLIB proxy-based advice.
*/
PROXY,
@@ -90,7 +90,6 @@ import org.springframework.util.ClassUtils;
* @see ScannedGenericBeanDefinition
* @see CandidateComponentsIndex
*/
@SuppressWarnings("removal") // components index
public class ClassPathScanningCandidateComponentProvider implements EnvironmentCapable, ResourceLoaderAware {
static final String DEFAULT_RESOURCE_PATTERN = "**/*.class";
@@ -452,9 +451,9 @@ public class ClassPathScanningCandidateComponentProvider implements EnvironmentC
private Set<BeanDefinition> scanCandidateComponents(String basePackage) {
Set<BeanDefinition> candidates = new LinkedHashSet<>();
try {
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
String packageSearchPattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
resolveBasePackage(basePackage) + '/' + this.resourcePattern;
Resource[] resources = getResourcePatternResolver().getResources(packageSearchPath);
Resource[] resources = getResourcePatternResolver().getResources(packageSearchPattern);
boolean traceEnabled = logger.isTraceEnabled();
boolean debugEnabled = logger.isDebugEnabled();
for (Resource resource : resources) {
@@ -537,13 +536,13 @@ public class ClassPathScanningCandidateComponentProvider implements EnvironmentC
* @return whether the class qualifies as a candidate component
*/
protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {
for (TypeFilter tf : this.excludeFilters) {
if (tf.match(metadataReader, getMetadataReaderFactory())) {
for (TypeFilter filter : this.excludeFilters) {
if (filter.match(metadataReader, getMetadataReaderFactory())) {
return false;
}
}
for (TypeFilter tf : this.includeFilters) {
if (tf.match(metadataReader, getMetadataReaderFactory())) {
for (TypeFilter filter : this.includeFilters) {
if (filter.match(metadataReader, getMetadataReaderFactory())) {
return isConditionMatch(metadataReader);
}
}

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