Compare commits

...

771 Commits

Author SHA1 Message Date
Spring Builds c04290e9ab Release v6.1.5 2024-03-14 09:46:23 +00:00
rstoyanchev 381f790329 Extract reusable checkSchemeAndPort method
Closes gh-32440
2024-03-14 08:45:38 +00:00
Juergen Hoeller f5a3658535 Upgrade to Protobuf 3.25.3, Woodstox 6.6.1, JsonPath 2.9, QDox 2.1 2024-03-13 18:06:44 +01:00
Juergen Hoeller 54a6d89da7 Additional unit tests for operations on empty UriTemplate
See gh-32432
2024-03-13 18:06:17 +01:00
Stéphane Nicoll 2922a82275 Merge pull request #32432 from bsgrd
* pr/32432:
  Polish "Allow UriTemplate to be built with an empty template"
  Allow UriTemplate to be built with an empty template

Closes gh-32432
2024-03-13 17:27:52 +01:00
Stéphane Nicoll a34ceb405c Polish "Allow UriTemplate to be built with an empty template"
See gh-32432
2024-03-13 17:21:46 +01:00
Kasper Bisgaard 1b25a1506a Allow UriTemplate to be built with an empty template
See gh-32432
2024-03-13 17:20:08 +01:00
Juergen Hoeller 723c94e5ac Polishing 2024-03-12 20:10:01 +01:00
Juergen Hoeller e5a69dcfdf Upgrade to Reactor 2023.0.4 and Micrometer 1.12.4
Includes AspectJ 1.9.21.1, Groovy 4.0.19, Tomcat 10.1.19, Jetty 12.0.7, Jackson 2.15.4, OpenPDF 1.3.42, Mockito 5.11, Checkstyle 10.14.1

Closes gh-32420
Closes gh-32431
2024-03-12 20:07:58 +01:00
Xednar c2248c968c Update Javadoc in DefaultUserDestinationResolver
Closes gh-32272
2024-03-12 11:43:24 +00:00
Sébastien Deleuze 9cc74e78f8 Refine "Redirecting to a resource" section code sample
The commit updates the code sample to use a null element friendly list.

Closes gh-32423
2024-03-12 12:22:37 +01:00
Brian Clozel 9910df85cd Remove observation context from ClientRequest
Prior to this commit, gh-31609 added the current observation context as
a request attribute for `WebClient` calls. While it was not confirmed as
the main cause, this feature was linked to several reports of memory
leaks. This would indeed attach more memory to the request object graph
at runtime - although it shouldn't prevent its collection by the GC.

This commit removes this feature and instead developers should get the
current observation from the reactor context if they wish to interact
with it.

Closes gh-32198
2024-03-12 09:49:00 +01:00
Stéphane Nicoll 88b3844d9b Fix default value in ReactorNettyClientRequestFactory#setExchangeTimeout
Closes gh-32419
2024-03-12 08:13:42 +01:00
Sébastien Deleuze 80f3be6577 Replace getJvmErasure by getClassifier
Should be slightly faster.

See gh-32334
2024-03-11 13:37:41 +01:00
Sébastien Deleuze 946082f806 Refine publisher type check in CoroutinesUtils
See gh-32390
2024-03-11 13:15:54 +01:00
ZeroCyan 78fb378aef Fix order of sections in Validation chapter of reference manual
Closes gh-32408
2024-03-10 17:41:09 +01:00
Sam Brannen b4e743614e Restore link to Jakarta Servlet issue tracker 2024-03-09 16:30:14 +01:00
Stéphane Nicoll accf7ff645 Merge pull request #32403 from qeeqez
* pr/32403:
  Polish "Fix Javadoc"
  Fix Javadoc

Closes gh-32403
2024-03-09 16:02:51 +01:00
Stéphane Nicoll 4983a802a7 Polish "Fix Javadoc"
See gh-32403
2024-03-09 16:02:01 +01:00
Maksim Sasnouski abdccffa39 Fix Javadoc
This commit fixes various Javadoc issues across the code base.

See gh-32403
2024-03-09 16:02:00 +01:00
Juergen Hoeller c1287d48e2 Polishing 2024-03-08 19:31:01 +01:00
Sam Brannen 528029a0ba Document that SpEL expressions using array construction cannot be compiled
Closes gh-32401
2024-03-08 15:49:08 +01:00
Sam Brannen fea1464562 Ensure SpEL can compile an expression indexing into a boolean array
Closes gh-32400
2024-03-08 15:32:57 +01:00
Brian Clozel f6bc828569 Set error on observation in WebClient instrumentation
Prior to this commit, error signals flowing from the client response
publisher in `WebClient` would be set on the `Observation.Context`. This
is enough for the observation convention to collect data about the error
but observation handlers are not notified of this error.

This commit sets the error instead on the observation directly to fix
this issue.

Fixes gh-32389
2024-03-08 11:33:45 +01:00
Yanming Zhou 0e279fe666 Polishing
Closes gh-32397
2024-03-08 09:25:03 +01:00
rstoyanchev 56a1c810b5 Remove IOException that's not thrown from Javadoc 2024-03-07 16:05:15 +00:00
rstoyanchev dec5265354 Use wrapped response in HandlerFunctionAdapter
webmvc.fn now also uses the StandardServletAsyncWebRequest wrapped response
to enforce lifecycle rules from Servlet spec (section 2.3.3.4).

See gh-32340
2024-03-07 14:47:50 +00:00
Sébastien Deleuze 579dbc48d7 Optimize Coroutine invocations
KClass instantiation in CoroutinesUtils is suboptimal, and should be
replaced by KTypes#isSubtypeOf checks using pre-instantiated types for
Flow, Mono and Publisher.

This commit impact on performances is significant since a throughput
increase between 2x and 3x has been measured on basic endpoints.

Closes gh-32390
2024-03-07 14:27:47 +01:00
Simon Baslé 6d9a2eb9b8 Improve fix of duplicate upstream subscription during reactive cache put
This commit fixes an issue where a Cacheable method which returns a
Flux (or multi-value publisher) will be invoked once, but the returned
publisher is actually subscribed twice.

The previous fix 988f3630c would cause the cached elements to depend on
the first usage pattern / request pattern, which is likely to be too
confusing to users. This fix reintroduces the notion of exhausting the
original Flux by having a second subscriber dedicated to that, but uses
`refCount(2)` to ensure that the original `Flux` returned by the cached
method is still only subscribed once.

Closes gh-32370
2024-03-07 12:08:28 +01:00
Sébastien Deleuze c1d4b610ca Refine Kotlin inline class optimizations
Closes gh-32334
2024-03-07 11:11:20 +01:00
rstoyanchev 5f601ceb45 Mark response errors from @ExceptionHandler as handled
Also fix a couple of related issues:
- add AsyncRequestNotUsableException to the list of exceptions
that imply response issues.
- handle exceptions from @ExceptionHandler regardless of whether
thrown immediately or via Publisher.

Closes gh-32359
2024-03-06 18:17:13 +00:00
Juergen Hoeller 0955f541cb Polishing 2024-03-06 18:03:36 +01:00
Juergen Hoeller e5e61dfa3f Ignore scheduled task exceptions after shutdown
Includes suppression after logging, not propagating exceptions to the thread itself.

Closes gh-32381
See gh-32298
2024-03-06 18:03:31 +01:00
Simon Baslé 988f3630c4 Avoid duplicate upstream subscription during reactive cache put
This commit fixes an issue where a Cacheable method which returns a
Flux (or multi-value publisher) will be invoked once, but the returned
publisher is actually subscribed twice.

By using the Reactor `tap` operator, we ensure that we can emit values
downstream AND accumulate emitted values into the List with a single
subscription.

The SignalListener additionally handles scenarios involving cancel,
for instance in case of a `take(1)` in the chain. In that case values
emitted up until that point will have been stored into the List buffer,
so we can still put it in the cache. In case of error, no caching occurs
and the internal buffer is cleared. This implementation also protects
against competing onComplete/onError signals and cancel signals.

Closes gh-32370
2024-03-05 18:32:32 +01:00
Juergen Hoeller a0ae849856 Polishing 2024-03-05 18:23:13 +01:00
rstoyanchev ef0717935b Test wrapping of response for async request
The following adjustments are also made as a result:
- Use int to check if lock is held and unlock is needed, given that
for non-async requests we don't need to obtain a lock.
- Protect access methods getOutputStream and getWriter with the
same locking and state checks.

Closes gh-32340
2024-03-05 11:42:03 +00:00
rstoyanchev 822e2447a0 Polishing StandardServletAsyncWebRequestTests
See gh-32340
2024-03-05 11:42:03 +00:00
Sébastien Deleuze cfd0aee4db Polish and add MockMvcExtensionsTests.queryParameter
Closes gh-32371
2024-03-05 10:59:12 +01:00
corby kim 132fbe228f Add query parameters to MockMvc Kotlin DSL
See gh-32371
2024-03-05 10:56:41 +01:00
Juergen Hoeller 4300fec023 Restore ability to return original method at ClassUtils level as well
Closes gh-32365
2024-03-04 23:48:26 +01:00
Juergen Hoeller e9110c0729 Polishing 2024-03-04 22:48:52 +01:00
Juergen Hoeller 24759a75f4 Restore ability to return original method for proxy-derived method
Closes gh-32365
2024-03-04 22:48:46 +01:00
Sébastien Deleuze 7493ce86b6 Fix ServletResponseHttpHeaders#get null handling
ServletResponseHttpHeaders#get should be annotated with `@Nullable` and
return null instead of a singleton list containing null when there is no
content type header.

Closes gh-32362
2024-03-04 14:43:09 +01:00
Sébastien Deleuze ce9dc19a3c Optimize content type parsing
This commit avoids calling HttpHeaders#getContentType multiple times in
ServletServerHttpResponse#writeHeaders.

Closes gh-32361
2024-03-04 14:43:09 +01:00
rstoyanchev 4b96cd28c0 Add locking in ServletResponse#flushBuffer
In addition to using the ServletOutputStream, it's also possible to call
ServletResponse#flushBuffer, so the ServletOutputStream wrapper logic needs
to apply there as well.

See gh-32340
2024-03-04 13:35:46 +00:00
Sébastien Deleuze 516a203703 Support nullable Kotlin value class arguments
This commit skips the value class parameter instantiation for nullable
types when a null argument is passed.

Closes gh-32353
2024-03-03 22:26:21 +01:00
rstoyanchev 877e0b1483 Improve concurrent handling of result in WebAsyncManager
1. Use state transitions
2. Increase synchronized scope in setConcurrentResultAndDispatch

See gh-32340
2024-03-03 20:44:52 +00:00
rstoyanchev 379ffac508 Add state and response wrapping to StandardServletAsyncWebRequest
The wrapped response prevents use after AsyncListener onError or completion
to ensure compliance with Servlet Spec 2.3.3.4.

The wrapped response is applied in RequestMappingHandlerAdapter.

The wrapped response raises AsyncRequestNotUsableException that is now
handled in DefaultHandlerExceptionResolver.

See gh-32340
2024-03-03 20:44:36 +00:00
Sam Brannen 380184e85a Support SpEL compilation of #root or #this with non-public type
Prior to this commit, if a Spring Expression Language (SpEL) expression
referenced the root context object via the #root or #this variable, we
inserted a checkcast in the generated byte code that cast the object to
its concrete type. However if the root context object's type was
non-public, that resulted in an IllegalAccessError when the compiled
byte code was executed.

VariableReference.getValueInternal() already contains a solution for
global variables which inserts a checkcast to Object in the generated
byte code instead of to the object's concrete non-public type.

This commit therefore applies the same logic to #root (or #this when
used to reference the root context object) that is already applied to
global variables.

Closes gh-32356
2024-03-03 14:49:42 +01:00
Sam Brannen 5cba32df32 Polish SpEL's VariableReference 2024-03-02 18:03:44 +01:00
Sam Brannen 11c40b5c1c Restructure SpEL indexer compilation tests 2024-03-02 18:03:44 +01:00
Sébastien Deleuze 227e75dae4 Support nullable Kotlin value class arguments
This commit refines WebMVC and WebFlux argument resolution in order to
convert properly Kotlin value class arguments by using the type of the
value instead of the type of the value class.

Closes gh-32353
2024-03-01 16:38:26 +01:00
Sam Brannen de828e9764 Improve documentation for @⁠Sql execution phases regarding lifecycle
Closes gh-32343
2024-03-01 14:37:31 +01:00
Sébastien Deleuze 85a781d517 Instantiate value class parameters with Kotlin reflection
In order to invoke the init block and to improve the maintainability.

Closes gh-32324
2024-03-01 11:50:19 +01:00
Stéphane Nicoll 7f916e0ee3 Merge pull request #32349 from qeeqez
* pr/32349:
  Upgrade to com.gradle.enterprise 3.16.2

Closes gh-32349
2024-02-29 17:16:03 +01:00
Maksim Sasnouski 960e885f88 Upgrade to com.gradle.enterprise 3.16.2
See gh-32349
2024-02-29 17:15:26 +01:00
Arjen Poutsma bf8f398c19 Merge pull request #32318 from kilink:http-headers-getAcceptLanguageAsLocales-optimization
* gh-32318:
  Polishing external contribution
  Optimize HttpHeaders.getAcceptLanguageAsLocales
2024-02-29 15:54:52 +01:00
Arjen Poutsma 33705516ff Polishing external contribution
See gh-32318
2024-02-29 15:51:29 +01:00
Patrick Strawderman beb415dfa3 Optimize HttpHeaders.getAcceptLanguageAsLocales
The HttpHeaders.getAcceptLanguageAsLocales was incurring overhead from
using a Stream, as well as calling the fairly expensive
Locale.getDisplayName method.

Switch to using an ArrayList, and skipping over wildcard ranges to avoid
needing to check the display name.

Closes gh-32318
2024-02-29 15:36:55 +01:00
Juergen Hoeller d45c0e6b8a Upgrade to Undertow 2.3.12, OpenPDF 1.3.41, JRuby 9.4.6 2024-02-28 21:42:16 +01:00
Juergen Hoeller 154ca54c9f Polishing 2024-02-28 21:40:08 +01:00
Juergen Hoeller f22a1eece4 Polishing 2024-02-28 19:14:37 +01:00
Juergen Hoeller 6d9736acd0 Direct reference to PushBuilder API on Servlet 5.0 baseline
See gh-29435
2024-02-28 19:14:30 +01:00
Sébastien Deleuze 0de3b30029 Provide guidelines for using Kotlin properties with proxies
A typical use case is `@Scope` and its popular `@RequestScope`
specialization.

Closes gh-32287
2024-02-28 18:33:39 +01:00
Sébastien Deleuze 45c21042f6 Optimize Kotlin inline class checks
This commit fixes a performance regression caused by gh-31698,
and more specifically by KClass#isValue invocations which are slow since
they load the whole module to find the class to get the descriptor.

After discussing with the Kotlin team, it has been decided that only
checking for the presence of `@JvmInline` annotation is enough for
Spring use case.

As a consequence, this commit introduces a new
KotlinDetector#isInlineClass method that performs such check, and
BeanUtils, CoroutinesUtils and WebMVC/WebFlux InvocableHandlerMethod
have been refined to leverage it.

Closes gh-32334
2024-02-28 17:18:57 +01:00
Sam Brannen 5830aac1d4 Omit parameter names in REST Clients section of reference docs
For consistency with other examples, this commit omits `method` parameter
names in the "Migrating from RestTemplate to RestClient" section of the
reference docs.

Closes gh-32335
2024-02-28 10:41:50 +01:00
Sam Brannen 0eb61c0f72 Polish REST Clients section 2024-02-28 10:34:57 +01:00
Sébastien Deleuze dc1ef23780 Refine *HttpMessageConverter#getContentLength null safety
Closes gh-32325
2024-02-27 15:51:52 +01:00
Sam Brannen cca440eb8e Do not cache Content-Type in ContentCachingResponseWrapper
Based on feedback from several members of the community, we have
decided to revert the caching of the Content-Type header that was
introduced in ContentCachingResponseWrapper in 375e0e6827.

This commit therefore completely removes Content-Type caching in
ContentCachingResponseWrapper and updates the existing tests
accordingly.

To provide guards against future regressions in this area, this commit
also introduces explicit tests for the 6 ways to set the content length
in ContentCachingResponseWrapper and modifies a test in
ShallowEtagHeaderFilterTests to ensure that a Content-Type header set
directly on ContentCachingResponseWrapper is propagated to the
underlying response even if content caching is disabled for the
ShallowEtagHeaderFilter.

See gh-32039
Closes gh-32317
2024-02-26 17:52:56 +01:00
Sam Brannen 497aa3c069 Polish ShallowEtagHeaderFilterTests 2024-02-26 17:44:48 +01:00
Juergen Hoeller 479879c53a Polishing 2024-02-26 13:40:21 +01:00
Juergen Hoeller 2e57603310 Try type conversion for unique fallback write method as well
Closes gh-32329
See gh-32159
2024-02-26 13:40:05 +01:00
Sam Brannen be45481d70 Return unique set from ContentCachingResponseWrapper.getHeaderNames()
Prior to this commit, getHeaderNames() returned duplicates for the
Content-Type and Content-Length headers if they were set in the wrapped
response as well as in ContentCachingResponseWrapper.

This commit fixes that by returning a unique set from getHeaderNames().

In addition, this commit introduces a new test in
ContentCachingResponseWrapperTests to verify the expected behavior for
Content-Type and Content-Length headers that are set in the wrapped
response as well as in ContentCachingResponseWrapper.

See gh-32039
See gh-32317
2024-02-25 16:17:22 +01:00
Sam Brannen 5680d20637 Honor Content-[Type|Length] headers from wrapped response again
Commit 375e0e6827 introduced a regression in
ContentCachingResponseWrapper (CCRW). Specifically, CCRW no longer
honors Content-Type and Content-Length headers that have been set on
the wrapped response and returns null for those header values if they
have not been set directly on the CCRW.

This commit fixes this regression as follows.

- The Content-Type and Content-Length headers set in the wrapped
  response are honored in getContentType(), containsHeader(),
  getHeader(), and getHeaders() unless those headers have been set
  directly on the CCRW.

- In copyBodyToResponse(), the Content-Type in the wrapped response is
  only overridden if the Content-Type has been set directly on the CCRW.

See gh-32039
Closes gh-32317
2024-02-24 16:37:22 +01:00
Sam Brannen 8787381892 Polish ContentCachingResponseWrapper[Tests] 2024-02-24 16:37:14 +01:00
Juergen Hoeller 3cc64968b9 Consistent nullability for internal field access 2024-02-24 08:21:37 +01:00
Juergen Hoeller 4dc3eac864 Polishing 2024-02-22 16:56:22 +01:00
Juergen Hoeller 0188270138 Clarify transaction metadata exposed from currentTransactionStatus()
Closes gh-32310
2024-02-22 16:56:17 +01:00
Sébastien Deleuze 9430b24eaf Adapt Hibernate native support for HHH-17643
This commit adapts Hibernate native support to handle
the changes performed as part of HHH-17643 which impacts
Hibernate versions 6.4.3+ and 6.2.21+.

It ignores the BytecodeProvider services loaded by the
service loader feature in order to default to the
"no-op" provider with native, and makes the substitutions
more lenient when a substituted field or method does not
exist.

gh-32314 is expected to remove the need for such
substitutions which are not great for maintainability
by design.

Closes gh-32311
2024-02-22 16:30:32 +01:00
Juergen Hoeller 41433d445e Polishing 2024-02-21 22:58:42 +01:00
Juergen Hoeller 7ffeb59b40 Polishing 2024-02-21 22:45:39 +01:00
Juergen Hoeller 8d4953d8d6 Add test for cleanup after configuration class creation failure
See gh-23343
2024-02-21 22:45:32 +01:00
Brian Clozel f440d8719c Prepare JDK 23 early access build in CI
See gh-32090
2024-02-21 18:23:38 +01:00
Stéphane Nicoll 5d6501c75e Revisit stored procedure detection
This commit revisits the improved detection algorithm for stored
procedure as, unfortunately, certain JDBC drivers do not support
the documented pattern for schema and procedure name.

To work around this limitation, this commit applies the escaping of
wildcard characters to the case where multiple procedures have been
found for a given search.

Closes gh-32295
2024-02-21 15:54:34 +01:00
Juergen Hoeller 93f0ec2fa1 Polishing 2024-02-20 15:42:15 +01:00
Juergen Hoeller 85c9279431 Consistent default error handling/logging for all scheduled tasks
Closes gh-32298
2024-02-20 15:42:07 +01:00
Stéphane Nicoll 06a39f166e Consistent handling of AssertProvider implementations 2024-02-20 10:19:19 +01:00
Stéphane Nicoll 46bd133892 Upgrade CI image to Java 22+36 RC 2024-02-19 10:52:10 +01:00
Juergen Hoeller 7bb9e85723 Avoid trivial static import 2024-02-16 22:43:56 +01:00
Juergen Hoeller 3aae7a66e6 Polishing 2024-02-16 22:27:09 +01:00
Stéphane Nicoll 26ca7c49fb Merge pull request #32281 from kilink
* pr/32281:
  Update copyright year of changed files
  Use Spliterator of underlying collection

Closes gh-32281
2024-02-16 08:36:20 +01:00
Stéphane Nicoll 6b8105aef2 Update copyright year of changed files
See gh-32281
2024-02-16 08:33:17 +01:00
Patrick Strawderman 481283d2f1 Use Spliterator of underlying collection
Delegate to the spliterator method of the underlying collection in
MutablePropertyValues and MutablePropertySources. In both cases, those
collection types have specialized Spliterator implementations.
Delegating to these Spliterators also means the characteristics of the
Spliterator are properly set.

See gh-32281
2024-02-16 08:32:41 +01:00
Stéphane Nicoll 4230c41d97 Initiate 6.1.x branch 2024-02-15 12:59:07 +01:00
Spring Builds b082348e61 Next development version (v6.1.5-SNAPSHOT) 2024-02-15 10:22:18 +00:00
Juergen Hoeller f41c7ceaf7 Upgrade to Undertow 2.3.11 2024-02-15 10:55:28 +01:00
Juergen Hoeller 9a068869ef Upgrade to Reactor 2023.0.3, Micrometer 1.12.3, Context Propagation 1.1.1
Includes Groovy 4.0.18, Netty 4.1.107, OpenPDF 1.3.40, Protobuf 3.25.2
2024-02-15 10:13:47 +01:00
Sébastien Deleuze d147609e04 Update a reference to the build pipeline 2024-02-15 10:11:14 +01:00
Stéphane Nicoll e9a359f873 Fix pipeline reference 2024-02-15 10:08:19 +01:00
rstoyanchev 78f0688ed0 Fix javadoc error
See gh-32205
2024-02-14 16:48:58 +00:00
rstoyanchev 504b7619bd WebSocketMessageBrokerConfigurer allows to configure Lifecycle phase
Closes gh-32205
2024-02-14 16:26:33 +00:00
Brian Clozel f9ae54d91e Allow sending SSE events without data
Prior to this commit, the SseBuilder API in WebMvc.fn would only allow
to send Server-Sent Events with `data:` items in them. The spec doesnn't
disallow this and other specifications rely on such patterns to signal
the completion of a stream, like:

```
event:next
data:some data

event:complete

```

This commit adds a new `send()` method without any argument that sends
the buffered content (id, event comment and retry) without data.

Fixes: gh-32270
2024-02-14 16:58:02 +01:00
Cirus Thenter 2284254d39 Fix Kotlin syntax errors in RestClient builder example
Closes gh-32265
2024-02-14 13:52:33 +01:00
Sébastien Deleuze 6e9607ce99 Use double dot in META-INF/aop.xml documentation
Closes gh-32264
2024-02-14 10:42:15 +01:00
Arjen Poutsma b4bec4ca61 Allow repeatable writes in Client Interceptors
See gh-31449
2024-02-14 10:05:26 +01:00
Stéphane Nicoll 48da9524c3 Polish 2024-02-14 02:40:02 +01:00
Sam Brannen 68189f3de9 Document that "functions are variables" in SpEL evaluation contexts
Although EvaluationContext defines the API for setting and looking up
variables, the internals of the Spring Expression Language (SpEL)
actually provide explicit support for registering functions as
variables.

This is self-evident in the two registerFunction() variants in
StandardEvaluationContext; however, functions can also be registered as
variables when using the SimpleEvaluationContext.

Since custom functions are also viable in use cases involving the
SimpleEvaluationContext, this commit documents that functions may be
registered in a SimpleEvaluationContext via setVariable().

This commit also explicitly documents the "function as a variable"
behavior in the class-level Javadoc for both StandardEvaluationContext
and SimpleEvaluationContext, as well as in the reference manual.

Closes gh-32258
2024-02-13 17:22:35 +01:00
Sam Brannen 10bc93c058 Polishing 2024-02-13 17:22:35 +01:00
Simon Baslé 9b93c948a7 Infer reflection hints for Jackson annotations builder attributes
This notably enables Jackson to reflectively call a user-provided
builder class and invoke its declared methods (setters and build) in
a native app.

Closes gh-32238
2024-02-13 15:14:08 +01:00
Sébastien Deleuze abe381488a Add missing RequestPredicate variants in coRouter
Closes gh-32256
2024-02-13 14:50:49 +01:00
Sébastien Deleuze cc6dd19324 Polishing 2024-02-13 14:29:18 +01:00
Sébastien Deleuze 2fe3321813 Fix pathExtension null-safety in Kotlin DSLs
Closes gh-32254
2024-02-13 14:24:19 +01:00
Sébastien Deleuze 8c3fc8c549 Add documentation for functional resource handling
Closes gh-27257
2024-02-13 13:36:48 +01:00
Sébastien Deleuze d3ca6f9f6a Add resource redirection to WebMVC functional router
See gh-27257
2024-02-13 13:24:13 +01:00
Sébastien Deleuze 2d7b2e59b6 Add resource redirection to WebFlux functional router
See gh-27257
2024-02-13 13:24:13 +01:00
Sam Brannen 46108deff4 Make SimpleEvaluationContext.Builder final and its constructor private
Closes gh-32253
2024-02-13 13:18:54 +01:00
Sam Brannen 4454b3b5ef Polishing 2024-02-13 13:15:51 +01:00
rstoyanchev 2dd22f64e1 Improve cancellation of read/write inactivity
The cancellation of read and write inactivity tasks was done via
WebSocketHandler#afterConnectionClosed, relying on the WebSocket
library to always invoke the callback.

This change moves the cancellation to the `close` method instead
that in turn is called from DefaultStompSession#resetConnection,
in effect making the cancellation more proactive and aligned with
connection cleanup in DefaultStompSession vs relying on a
subsequent call from the WebSocket library after the connection
is closed.

Closes gh-32195
2024-02-13 11:17:34 +00:00
rstoyanchev 6be0432e3d Use ConnectionLostException after heartbeat failures
ConnectionLostException was applies only after the WebSocket library
notified us of a session close. However, read inactivity and heartbeat
send failures are also cases of the connection being lost rather than
closed intentionally.

This commit also ensures resetConnection is called after a heartbeat
write failure, consistent with other places where a transport error
is handled that implies the connection is lost.

See gh-32195
2024-02-13 11:17:34 +00:00
rstoyanchev 6a5953dca3 Polishing in WebSocketStompClient
See gh-32195
2024-02-13 11:17:34 +00:00
Juergen Hoeller b4153618a4 Consistent Lock field declaration (instead of ReentrantLock field type) 2024-02-13 11:07:20 +01:00
Juergen Hoeller 0b09f1e12f Use ReentrantLock instead of synchronization for concurrency throttle
Closes gh-32251
2024-02-13 11:03:40 +01:00
rstoyanchev 120ea0a51c Update user info pattern
Closes gh-32211
2024-02-13 07:09:46 +00:00
Stéphane Nicoll c46d6286ee Review AOT recommendations in the reference guide
This commit focuses on improving the AOT section on programmatic
registration of additional beans. This makes it more clear that a
`BeanDefinitionRegistry` must be used and that singletons are not
processed.

Closes gh-32240
Closes gh-32241
2024-02-12 16:48:26 +01:00
Arjen Poutsma 750cb73902 Introduce single-value request predicates
This commit introduces new HTTP method, Content-Type, and Accept header
request predicates that handle single values. Previously, these
predicates were always dealt with as single-value collections, which
introduced computational overhead.

Closes gh-32244
2024-02-12 16:09:00 +01:00
rstoyanchev 5851cdc679 Refine invocation of checkSessions
It makes more sense to call this from afterConnectionEstablished as it
relates to the creation of new sessions.

See gh-32195
2024-02-12 12:50:45 +00:00
Stéphane Nicoll 2e833d908a Merge pull request #32231 from OlgaMaciaszek
* pr/32231:
  Polish "Document @RequestAttribute"
  Document @RequestAttribute

Closes gh-32231
2024-02-12 10:39:00 +01:00
Stéphane Nicoll 728d5eeb74 Polish "Document @RequestAttribute"
See gh-32231
2024-02-12 10:38:29 +01:00
Olga MaciaszekSharma 89e34ae5ff Document @RequestAttribute
See gh-32231
2024-02-12 10:35:20 +01:00
Stéphane Nicoll 9ee7c6383f Merge pull request #32232 from OlgaMaciaszek
* pr/32232:
  Update copyright year of changed file
  Fix supportsRequestAttributes for RestClientAdapter

Closes gh-32232
2024-02-12 10:31:26 +01:00
Stéphane Nicoll ee801d1b28 Update copyright year of changed file
See gh-32232
2024-02-12 10:29:16 +01:00
Olga MaciaszekSharma eebdff23e7 Fix supportsRequestAttributes for RestClientAdapter
Previously, RestClientAdapter claimed that it supports request
attributes when, in fact, it does not. This commit updates the
implementation accordingly.

See gh-32232
2024-02-12 10:27:32 +01:00
Juergen Hoeller a2000dba33 Leniently accept tasks after context close in lifecycle stop phase
Schedulers remain strict, just plain executors are lenient on shutdown now.
An early shutdown for executors can be enforced via setStrictEarlyShutdown.

Closes gh-32226
2024-02-11 21:33:53 +01:00
Sam Brannen 4a3ef3e24a Document safe navigation semantics within compound expressions in SpEL
Closes gh-21827
2024-02-11 18:36:14 +01:00
Sam Brannen 4a5dc7c1b0 Document null-safe collection selection/projection support in SpEL
Closes gh-32208
2024-02-11 17:21:47 +01:00
Sam Brannen 347d085020 Polishing 2024-02-11 17:14:24 +01:00
Sam Brannen f295def2a8 Include function name in SpelMessage.INCORRECT_NUMBER_OF_ARGUMENTS_TO_FUNCTION
Closes gh-32239
2024-02-11 13:52:25 +01:00
Sam Brannen dc2dbd9700 Polishing 2024-02-11 13:52:25 +01:00
Sam Brannen 6b67972ec4 Polishing 2024-02-10 16:56:02 +01:00
Sam Brannen 64fc9ee301 Test function registration with SimpleEvaluationContext 2024-02-10 16:55:21 +01:00
Sam Brannen ce43d1b1da Simplify logic in ApplicationContextAwareProcessor.postProcessBeforeInitialization() 2024-02-10 15:46:38 +01:00
Sam Brannen dc73ec76fc Address TODOs in SpEL's Indexer
This commit deletes outdated TODOs and addresses a remaining "current"
TODO in SpEL's Indexer.
2024-02-10 15:39:18 +01:00
Sam Brannen 888e50175d Polish SpEL Javadocs and internals 2024-02-10 15:39:18 +01:00
Sam Brannen 1080c145e3 Polish ApplicationContextAwareProcessor 2024-02-10 11:46:09 +01:00
Stéphane Nicoll f726e806cd Merge pull request #32236 from spencergibb
* pr/32236:
  Polish "Fixes syntax error in JdbcClient examples"
  Fixes syntax error in JdbcClient examples

Closes gh-32236
2024-02-10 09:04:55 +01:00
Stéphane Nicoll b1f6401e4f Polish "Fixes syntax error in JdbcClient examples"
See gh-32236
2024-02-10 09:04:44 +01:00
Spencer Gibb 169b9abeef Fixes syntax error in JdbcClient examples
See gh-32236
2024-02-10 09:01:02 +01:00
Sam Brannen e72b523995 Polish SpEL support 2024-02-09 14:04:08 +01:00
Sébastien Deleuze 99bdc4211d Add Coroutines support to NonReactiveHandlerMethodPredicate
Closes gh-32227
2024-02-09 12:07:17 +01:00
Stéphane Nicoll d47c69746b Upgrade CI to Ubuntu Jammy 20240125 2024-02-08 19:03:42 +01:00
Sam Brannen 052bbcc530 Cache parameter types array in ClassUtils.findInterfaceMethodIfPossible() 2024-02-08 18:14:22 +01:00
Arjen Poutsma f9791664ef Implement MatchableHandlerMapping in RouterFunctionMapping
Closes gh-32221
2024-02-08 12:22:14 +01:00
Arjen Poutsma af44b3e6c0 Fix delegation in ServerRequest decorators
Closes gh-31955
2024-02-08 11:33:22 +01:00
John Gesimondo 2724c6d8fe Update beanvalidation.adoc
FieldErrro to FieldError
2024-02-07 23:27:31 +01:00
anil.senocak f7e5c9fbb2 In Kotlin variables should be defined as val or var. "mockMvc" was not defined properly 2024-02-07 23:27:11 +01:00
Patrick Strawderman 4486ab1cb7 Initialize Map with correct size in RequestPredicates
Fix another instance where a LinkedHashMap was initialized with an initial
capacity that would always cause a resize / rehash to occur. Switch to
CollectionUtils.newLinkedHashMap to size the map appropiately for the expected
number of items.

Closes gh-32215
2024-02-07 21:20:57 +01:00
Sam Brannen 78c96b6d78 Fix SpEL collection selection/projection examples in reference manual
This commit also updates and polishes the documentation tests.
2024-02-07 18:49:01 +01:00
Sam Brannen 43bbe8f3e8 Add tests for collection selection with Iterables 2024-02-07 13:32:22 +01:00
Sam Brannen 7d612e8958 Polishing 2024-02-07 13:29:33 +01:00
Sam Brannen 9a38355896 Improve tests for indexing and collection selection/projection in SpEL 2024-02-07 11:46:13 +01:00
Juergen Hoeller 3ecbc4de13 Polishing 2024-02-06 17:57:47 +01:00
Juergen Hoeller 81c156eefb Replace public hasRestTemplateDefaults() method with hasBaseUri()
See gh-32180
2024-02-06 17:57:27 +01:00
Juergen Hoeller d8c4a33bea Upgrade to SLF4J 2.0.12, Jetty 12.0.6, Apache HttpClient 5.3.1, OpenPDF 1.3.39, Mockito 5.10, Checkstyle 10.13 2024-02-06 17:54:26 +01:00
Juergen Hoeller cfa47fa4fb Polishing 2024-02-06 16:46:16 +01:00
Juergen Hoeller 80949eb30f Store known attribute names in session (for distributed sessions)
Closes gh-30463
2024-02-06 16:46:11 +01:00
Juergen Hoeller 4ed337247c Avoid sendError call when response committed already (Tomcat 10.1.16)
Closes gh-32206
2024-02-06 16:46:04 +01:00
Sam Brannen 81cdfafa78 Polishing 2024-02-06 12:55:25 +01:00
Patrick Strawderman d5cb1d9adb Initialize Map with correct size in RequestPredicates
Prior to this commit, the `RequestPredicates` would add new attributes
to the existing request attributes by creating a new `LinkedHashMap`
with the total number of elements as its new initial capacity.

This would not achieve optimal performance as initial resize or rehash
operations could be expected. Consistently using
`CollectionUtils#newLinkedHashMap` avoids this problem.

Closes gh-32201
2024-02-06 10:54:00 +01:00
Juergen Hoeller 9698dbc232 Add javadoc and rename merge method to mergeProperties
See gh-32118
2024-02-06 09:13:09 +01:00
Stéphane Nicoll 9c15b3fa4c Upgrade to AssertJ 3.25.3 2024-02-06 08:33:22 +01:00
Andrei Bastun c559ec4dfb Refactor ReloadableResourceBundleMessageSource
This change allows subclasses to reuse collecting and merging
algorithm when overriding getMergedProperties method.
2024-02-06 08:23:51 +01:00
Juergen Hoeller 341ac76209 Rely on HashSet for uniqueness of mapped names
See gh-32199
2024-02-06 08:20:15 +01:00
Juergen Hoeller 8ff102115a Let BeanPropertyRowMapper subclasses customize mapped names
Closes gh-32199
2024-02-05 18:24:38 +01:00
Brian Clozel f50a262cf2 Polish
See gh-32189
2024-02-05 11:16:32 +01:00
Arjen Poutsma c570f3b2da Fix off-by-one error in PartEvent part count
This commit fixes an off-by-one error in the
PartEventHttpMessageReader,  so that it no longer counts empty windows.

Closes gh-32122
2024-02-05 11:04:24 +01:00
Patrick Strawderman 0fdf759896 Optimize Map methods in ServletAttributesMap
ServletAttributesMap inherited default implementations of the size
and isEmpty methods from AbstractMap which delegates to the Set returned
by entrySet. ServletAttributesMap's entrySet method made this fairly
expensive, since it would copy the attributes to a List, then use a
Stream to build the Set. To avoid the cost, add implementations of
isEmpty / size that don't need to call entrySet at all.

Additionally, change entrySet to return a Set view that simply lazily
delegates to the underlying servlet request for iteration.

Closes gh-32189
2024-02-05 10:33:14 +01:00
Stéphane Nicoll c04d4da9a3 Polish 2024-02-05 09:11:04 +01:00
Sam Brannen b737f36f39 Upgrade to JUnit 5.10.2 2024-02-04 14:00:56 +01:00
Stéphane Nicoll 8d601384d3 Upgrade to Gradle 8.6
Closes gh-32192
2024-02-03 11:38:56 +01:00
Stéphane Nicoll ea52ecc5e0 Polish 2024-02-02 18:56:41 +01:00
Sam Brannen 9b5febea20 Document SpEL limitations for minimum values for numeric literals
Closes gh-20779
2024-02-02 15:43:42 +01:00
Sam Brannen 7627d8c6fc Improve layout for Literal Expressions section 2024-02-02 15:43:42 +01:00
Sam Brannen 20f91b7dc3 Fix tabs in SpEL "Classes Used in the Examples" section 2024-02-02 15:43:42 +01:00
Arjen Poutsma e15c150696 Only copy UriBuilderFactory when customized
This commit ensures that, when creating a RestClient.Builder from a
RestTemplate, the UriBuilderFactory is only copied if it has been
changed from the default values.
Before this commit, the UriBuilderFactory was effectively alway copied,
resulting in not being able to use a baseUrl.

This commit also introduces a small memory optimization in
DefaultUriBuilderFactory, so that default environment variables are
created lazily.

Closes gh-32180
2024-02-02 15:16:10 +01:00
Sam Brannen 7025b7aac2 Provide example for calculating Integer.MIN_VALUE with SpEL's power operator 2024-02-02 14:43:56 +01:00
Sam Brannen 1e432ff95d Improve documentation for overloaded operators in SpEL
See gh-32182
2024-02-02 14:39:09 +01:00
Juergen Hoeller ae17b11b70 Preserve overridden toString result in HandlerMethod copy constructor
Closes gh-32184
2024-02-01 19:14:11 +01:00
Juergen Hoeller 1a783f41aa Use target class for candidate retrieval but not for method matching
Closes gh-32181
See gh-21843
2024-02-01 18:59:45 +01:00
Sam Brannen 521fbfdb85 Update copyright headers in contribution 2024-02-01 17:58:06 +01:00
Siddik ACIL 87377d6f3e Fix modelAttribitePredicate typos
This commit replaces occurrences of modelAttribitePredicate with modelAttributePredicate
in HandlerMethodValidationException and the associated validator.

Closes gh-32183
2024-02-01 17:56:07 +01:00
Sam Brannen af2934c09b Document support for overloading operators in SpEL in reference manual
Closes gh-32182
2024-02-01 17:24:25 +01:00
Sam Brannen 17ee82e004 Organize and clean up SpEL documentation tests 2024-02-01 16:22:14 +01:00
Sam Brannen a82108ec73 Clarify semantics of SpEL's between operator
See gh-32140
2024-02-01 14:58:21 +01:00
Stéphane Nicoll d4401cc69a Polish 2024-02-01 14:40:02 +01:00
Sam Brannen 2367314b52 Polish SpEL chapter 2024-02-01 13:57:25 +01:00
Sam Brannen 80a3c1923f Link to Jakarta EL instead of mentioning Unified EL in SpEL overview
As a bit of trivia, Jakarta EL was originally Unified EL, which was
originally JSP EL, which was originally SPEL.

SPEL: Simplest Possible Expression Language
SpEL: Spring Expression Language

So one could say that SPEL inspired SpEL.
2024-02-01 13:50:14 +01:00
Sam Brannen c989cba963 Add Checkstyle rule to enforce use of class literals for primitives & void
This commit introduces a globally applied Checkstyle rule which
enforces the use of class literals for primitive types and void by
forbidding the use of the TYPE constants in Boolean, Character, Byte,
Short, Integer, Long, Float, Double, and Void.

For example, if MyClass uses one of the TYPE constants, the build will
now fail with a message similar to the following.

[ERROR] <...>/MyClass.java:39: Please use class literals for primitives and void -- for example, int.class instead of Integer.TYPE.
2024-02-01 12:51:35 +01:00
Juergen Hoeller 3d4d68c26f Run listener/send task locally as fallback on RejectedExecutionException
Closes gh-32171
2024-02-01 11:07:02 +01:00
Stéphane Nicoll b61552b9df Merge pull request #32176 from quaff
* pr/32176:
  Fix assertion in BeanWrapperAutoGrowingTests

Closes gh-32176
2024-02-01 09:35:01 +01:00
Yanming Zhou 615973cce4 Fix assertion in BeanWrapperAutoGrowingTests
See gh-32176
2024-02-01 09:34:32 +01:00
Juergen Hoeller 00577ed80a Polishing 2024-01-31 17:12:20 +01:00
Juergen Hoeller 9b2b485444 Disabled test for auto-growing nested map values
See gh-32154
2024-01-31 17:12:12 +01:00
Juergen Hoeller d586513d66 Introduce SqlBinaryValue/SqlCharacterValue as alternative to SqlLobValue
Includes direct byte array support via setBytes in StatementCreatorUtils.

Closes gh-32161
2024-01-31 17:12:05 +01:00
Sam Brannen 2b52582dff Polishing 2024-01-31 16:41:15 +01:00
Stéphane Nicoll 67958656e4 Polish 2024-01-31 15:01:03 +01:00
Stéphane Nicoll a4db0e7448 Merge pull request #32164 from quaff
* pr/32164:
  Polish contribution
  Polish StatementCreatorUtilsTests

Closes gh-32164
2024-01-31 08:57:53 +01:00
Stéphane Nicoll ef2cae36ac Polish contribution
See gh-32164
2024-01-31 08:57:11 +01:00
Yanming Zhou efaf41862c Polish StatementCreatorUtilsTests
See gh-32164
2024-01-31 08:56:59 +01:00
Juergen Hoeller af5acb6d34 Avoid pre-conversion attempt in case of overloaded write methods
Closes gh-32159
See gh-31872
2024-01-30 21:57:14 +01:00
Sam Brannen 067638ae6e Introduce ClassUtils.isVoidType() utility method 2024-01-30 16:27:34 +01:00
Sam Brannen 398cc01650 Polishing 2024-01-30 16:24:55 +01:00
Stéphane Nicoll 3a518b60e7 Merge pull request #32157 from jee14
* pr/32157:
  Upgrade copyright year of changed file
  Wrap ternary operator within parantheses

Closes gh-32157
2024-01-30 15:59:39 +01:00
Stéphane Nicoll 298f308ce1 Upgrade copyright year of changed file
See gh-32157
2024-01-30 15:59:06 +01:00
jee14 6ffb74def3 Wrap ternary operator within parantheses
See gh-32157
2024-01-30 15:57:51 +01:00
Stéphane Nicoll b55a4d3908 Prevent AOT from failing with spring-orm without JPA
This commit improves PersistenceManagedTypesBeanRegistrationAotProcessor
so that it does not attempt to load JPA classes when checking for the
presence of a PersistenceManagedTypes bean. To make it more clear a
check on the presence for JPA has been added to prevent the nested
classes to be loaded regardless of the presence of the bean.

Closes gh-32155
2024-01-30 15:43:07 +01:00
Sam Brannen db535863dd Consistently use class literals for primitive types
To improve consistency and avoid confusion regarding primitive types
and their wrapper types, this commit ensures that we always use class
literals for primitive types.

For example, instead of using the `Void.TYPE` constant, we now
consistently use `void.class`.
2024-01-30 15:26:12 +01:00
Stéphane Nicoll 95a3f3bb6e Upgrade CI to Java 22ea+33 2024-01-29 21:19:53 +01:00
Sam Brannen 84cce6018c Document the between operator in SpEL
Closes gh-32140
2024-01-29 18:34:12 +01:00
Sam Brannen e97fc7be38 Improve documentation for alternative textual operators in SpEL 2024-01-29 17:47:46 +01:00
Sam Brannen 9eae0ba50e Clean up warnings in build 2024-01-29 17:47:46 +01:00
Sam Brannen f3c8102882 Polish SpEL Tokenizer 2024-01-29 17:47:46 +01:00
Juergen Hoeller 005d5ef922 Polishing 2024-01-29 16:53:35 +01:00
Juergen Hoeller 5dc26460fb Eagerly initialize ZERO_NANOS constant 2024-01-29 16:48:08 +01:00
Sam Brannen 542502b2b6 Upgrade to AssertJ 3.25.2 2024-01-29 16:08:04 +01:00
Sam Brannen f6d8443781 Fix logic in SupplierUtils 2024-01-29 16:07:44 +01:00
Juergen Hoeller a44341ece3 Consistent method declaration order in Call/TableMetaDataProvider 2024-01-29 15:25:55 +01:00
Juergen Hoeller 969b18b0e8 Polishing 2024-01-29 15:25:43 +01:00
Juergen Hoeller 2e9d6a1d4e Polishing 2024-01-29 13:04:42 +01:00
Juergen Hoeller 7e5efdd8dd Reuse MapPropertySource for DynamicValuesPropertySource implementation
Closes gh-32110
2024-01-29 13:04:02 +01:00
Juergen Hoeller 08e6df8832 Revise shutdown phase log message and executor shutdown documentation
Closes gh-32109
2024-01-29 13:03:20 +01:00
Juergen Hoeller a738e4d5fd Explicit documentation note on cron-vs-quartz parsing convention
Closes gh-32128
2024-01-29 13:02:43 +01:00
Sébastien Deleuze 9c4b4ab81e Update basics.adoc
Closes gh-32145
2024-01-29 09:08:37 +01:00
Sam Brannen 0ee2d41528 Delete obsolete test utility method
Commit dc6ce30663 made this method obsolete.
2024-01-28 18:44:56 +01:00
Sam Brannen dc6ce30663 Polishing 2024-01-28 18:31:31 +01:00
Sam Brannen 62fa3f11c1 Correctly request primitive conversion in SpEL's Indexer
Prior to this commit, SpEL's Indexer incorrectly requested conversion
to wrappers instead of primitives when setting an element in a
primitive array.

This commit addresses this by requesting primitive conversion -- for
example, conversion to `int.class` instead of `Integer.class` when
setting a value in an `int[]` array.

For greater clarity, this commit also switches from using `TYPE`
constants in wrapper classes to primitive class literals -- for
example, from `Integer.TYPE` to `int.class`.

Closes gh-32147
2024-01-28 18:26:39 +01:00
Sam Brannen 2e56361fe4 Simplify implementation of internal VariableNotAvailableException
Since VariableNotAvailableException is not a public type, there is no
need to store the variable name in a field/property.
2024-01-28 17:05:30 +01:00
Sam Brannen 9b0162da49 Document increment and decrement operators in SpEL
Closes gh-32136
2024-01-28 16:43:55 +01:00
Sam Brannen ab98210e6d Polishing 2024-01-28 16:43:55 +01:00
Sam Brannen 97ad479250 Sync assignment operator test with example used in reference manual 2024-01-28 16:43:15 +01:00
Sam Brannen 24d6565cad Provide example for SpEL's exponential power operator (^) 2024-01-28 16:43:15 +01:00
Sam Brannen e34ad6bf5f Support prefix notation for SpEL increment/decrement in AST representation
Closes gh-32144
2024-01-28 15:21:07 +01:00
Sam Brannen 179b976964 Introduce tests for SpEL's Inc/Dec operators and polishing 2024-01-28 15:10:15 +01:00
Sam Brannen 1ff84671f8 Remove obsolete InProgressTests
Since SpEL is no longer "in progress", this commit removes the obsolete
InProgressTests class and moves all non-duplicated test cases to other
test classes.
2024-01-28 14:25:37 +01:00
Sam Brannen e1c22c5385 Clean up InProgressTests 2024-01-28 13:29:34 +01:00
Sam Brannen 3f30a1540c Additional SpEL setValue() tests and polishing 2024-01-28 13:29:22 +01:00
Sam Brannen ae9153e644 Polish SpEL-related tests 2024-01-27 19:09:02 +01:00
Sam Brannen 003407a7e3 Polish Javadoc for SpelEvaluationException and Expression 2024-01-27 19:09:02 +01:00
Stéphane Nicoll a7764dc61d Merge pull request #32141 from kzander91
* pr/32141:
  Polish "Simplify use of Reactor's cast operator"
  Simplify use of Reactor's cast operator

Closes gh-32141
2024-01-27 12:23:24 +01:00
Stéphane Nicoll 4b4778d569 Polish "Simplify use of Reactor's cast operator"
See gh-32141
2024-01-27 12:21:46 +01:00
Kai Zander d96a63944c Simplify use of Reactor's cast operator
This commit replaces filter(x -> x instanceof C).cast(C.class) with the
built-in ofType(C.class).

See gh-32141
2024-01-27 12:21:46 +01:00
Stéphane Nicoll ad7c090f4c Use catalog name in SimpleJdbcInsert
This commit harmonizes SimpleJdbcCall and SimpleJdbcInsert to
consistently use a catalog name if one is set. Previously,
SimpleJdbcInsert only used the catalog name to retrieve database
metadata.

Closes gh-32124
2024-01-26 17:58:41 +01:00
Sam Brannen b9bad56fc1 Document repeat and characer subtraction String operators in SpEL
Closes gh-32137
2024-01-26 17:39:15 +01:00
Sam Brannen fdf0a6f6c7 Polishing 2024-01-26 17:37:45 +01:00
Sam Brannen 86266b3d67 Update documentation for supported letters in variable names in SpEL
Closes gh-32138
2024-01-26 16:42:09 +01:00
Sam Brannen 68cf3b928b Remove obsolete reference to local variable support in SpEL 2024-01-26 16:21:50 +01:00
Sam Brannen 3024c6efa9 Polishing 2024-01-26 15:36:39 +01:00
Sam Brannen 500767a0fb Annotate core functional SPIs in SpEL with @FunctionalInterface
Prior to this commit, only the MethodFilter and ConstructorResolver
functional SPIs in the org.springframework.expression package were
annotated with @⁠FunctionalInterface.

For consistency, this commit designates each of the following
functional SPIs in that package as a @⁠FunctionalInterface as well.

- BeanResolver
- ConstructorExecutor
- MethodExecutor
- MethodResolver

Closes gh-32135
2024-01-26 14:46:10 +01:00
Sam Brannen 5b5319a659 Polishing 2024-01-26 14:45:44 +01:00
Sam Brannen 3ce7c52030 Update copyright headers 2024-01-26 14:11:37 +01:00
Sam Brannen bafcd1dc1c Remove SpEL README and tests for unsupported features 2024-01-26 13:41:50 +01:00
Sam Brannen 00b07659d9 Polish SpEL documentation and tests 2024-01-26 13:41:36 +01:00
Sam Brannen 9df94357de Enable test for argument conversion in SpEL 2024-01-26 12:43:34 +01:00
Sam Brannen 0e45f4cec4 Polishing 2024-01-26 11:08:58 +01:00
Stéphane Nicoll 8815788004 Allow an existing TaskExecutor to be configured in ChannelRegistration
This commit introduces a new method to configure an existing
TaskExecutor in ChannelRegistration. Contrary to
TaskExecutorRegistration, a ThreadPoolTaskExecutor is not necessary,
and it can't be further configured. This includes the thread name
prefix.

Closes gh-32081
2024-01-26 10:46:14 +01:00
Sam Brannen b7e4fa16ca Upgrade com.gradle.enterprise plugin to 3.16.1 2024-01-26 10:37:52 +01:00
Stéphane Nicoll 645d0db260 Merge pull request #32123 from wfouche
* pr/32123:
  Upgrade to gradle-versions-plugin 0.51.0

Closes gh-32123
2024-01-26 06:39:16 +01:00
Werner Fouché f4b3c768e8 Upgrade to gradle-versions-plugin 0.51.0
See gh-32123
2024-01-26 06:39:03 +01:00
Yanming Zhou 6b3bf554ce Fix typo
Introduced by commit f9726ae0c8

Closes gh-32111
2024-01-25 08:32:43 +01:00
Juergen Hoeller c6121da151 Polishing 2024-01-24 22:30:33 +01:00
Juergen Hoeller c5a75219ce Compare qualifier value arrays with equality semantics
Closes gh-32106
2024-01-24 22:30:28 +01:00
Juergen Hoeller 89e7174cc4 Share cached interceptors for entire Advised instance if possible
Closes gh-32104
2024-01-24 22:30:22 +01:00
Sébastien Deleuze 4f16297e45 Polishing
See gh-32074
2024-01-24 16:53:34 +01:00
Felipe 11898daed7 Add support for JSON streams to Kotlin Serialization
Closes gh-32074
2024-01-24 16:53:34 +01:00
Stéphane Nicoll 4d7da0059e Revert "Merge pull request #32071 from mnhock"
This reverts commit c3127249ac, reversing
changes made to 11c8b22c5a.

See gh-32071
2024-01-24 14:34:44 +01:00
Arjen Poutsma a4fcef4a62 Upgrade to jetty-reactive-httpclient:4.0.2
Closes gh-31931
2024-01-24 14:09:43 +01:00
Arjen Poutsma f2e267b494 Guard against multiple body subscriptions
Before this commit, the JDK and Jetty connectors do not have any
safeguards against multiple body subscriptions. Such as check has now
been added.

Closes gh-32100
2024-01-24 14:05:20 +01:00
rstoyanchev f9726ae0c8 Update description of web validation in docs
Closes gh-32082
2024-01-24 12:41:05 +00:00
Juergen Hoeller 199a675692 Declare current observation context as available since 6.0.15
See gh-31609
See gh-31646
2024-01-24 12:40:00 +01:00
Juergen Hoeller 2f921dd13d Declare allowPrivateNetwork as available since 5.3.32
See gh-28546
See gh-31974
2024-01-24 12:37:19 +01:00
Juergen Hoeller b92877990d Consistent nullability for concurrent result 2024-01-24 11:43:36 +01:00
Juergen Hoeller d7778c0212 Polishing 2024-01-23 18:31:31 +01:00
Juergen Hoeller 531ac89e7e Expose sendError message as default body
Closes gh-26720
2024-01-23 18:31:26 +01:00
Stéphane Nicoll 358555929d Revert "Merge pull request #32088 from Ryan-Dia"
This reverts commit 484aee069e, reversing
changes made to 6bd7f0231d.

See gh-32088
2024-01-23 14:46:08 +01:00
rstoyanchev 9230a7db16 WebAsyncManager handles disconnected client errors
See gh-32042
2024-01-22 17:17:18 +00:00
Sam Brannen 7e53a1f048 Re-enable Jaxb2MarshallerTests on JDK 22+
Since the bug in JDK 22-ea builds has been fixed [1], this commit
re-enables the disabled tests.

Verified using: OpenJDK Runtime Environment (build 22-ea+31-2314)

[1] https://bugs.openjdk.org/browse/JDK-8322214
2024-01-23 11:36:24 +01:00
Sam Brannen 45a1f98bd6 Polishing 2024-01-23 11:36:24 +01:00
Juergen Hoeller 5faace0eb3 Predetermine validation groups on initialization
Closes gh-32068
2024-01-23 11:15:12 +01:00
Juergen Hoeller 5656eaccb7 Avoid bridge resolution for method from unrelated class hierarchy
Closes gh-32087
2024-01-23 10:50:53 +01:00
Sam Brannen 3b2f6e74a6 Make assertions based on Annotation#toString() lenient
The behavior for the toString() implementation for annotations changed
in JDK 19, per my request to the JDK team (see link below).

Specifically, since JDK 19, the toString() implementation for annotation
proxies created by the JDK started using canonical names instead of
binary names for types.

See https://bugs.openjdk.org/browse/JDK-8281462
2024-01-23 10:41:40 +01:00
Stéphane Nicoll 484aee069e Merge pull request #32088 from Ryan-Dia
* pr/32088:
  Upgrade copyright year of changed file
  Use count in ParamsRequestCondition#getValueMatchCount

Closes gh-32088
2024-01-23 09:04:28 +01:00
Stéphane Nicoll def7075695 Upgrade copyright year of changed file
See gh-32088
2024-01-23 09:00:41 +01:00
ryan-dia 2daa074561 Use count in ParamsRequestCondition#getValueMatchCount
See gh-32088
2024-01-23 08:59:59 +01:00
Juergen Hoeller 6bd7f0231d Avoid double exists() call for common resource resolution
See gh-30369
See gh-18990
2024-01-22 13:40:51 +01:00
Brian Clozel 70d9f7c62c Record errors thrown by custom handler in RestTemplate observations
Prior to this commit, the `RestTemplate` observation instrumentation
would only record `RestClientException` and `IOException` as errors in
the observation. Other types of errors can be thrown by custom
components, such as `ResponseErrorHandler` and in this case they aren't
recorded with the observation.
Also, the current instrumentation does not create any observation scope
around the execution. While this would have a limited benefit as no
application code is executed there, developers could set up custom
components (such as, again, `ResponseErrorHandler`) that could use
contextual logging with trace ids.

This commit ensures that all `Throwable` are recorded as errors with the
observations and that an observation `Scope` is created around the
execution of the client exchange.

Fixes gh-32060
2024-01-22 11:03:57 +01:00
Sam Brannen 5856d2e54e Polish contribution
See gh-32069
2024-01-21 16:27:59 +01:00
mnhock a8fa98e2a6 Remove unnecessary semicolons in enum declarations
Closes gh-32069
2024-01-21 16:25:36 +01:00
Stéphane Nicoll 73725905ba Merge pull request #32072 from mnhock
* pr/32072:
  Use 'Map.getOrDefault' rather than explicit check with fallback

Closes gh-32072
2024-01-20 14:42:50 +01:00
mnhock 1e71d3d363 Use 'Map.getOrDefault' rather than explicit check with fallback
See gh-32072
2024-01-20 14:37:23 +01:00
Stéphane Nicoll c3127249ac Merge pull request #32071 from mnhock
* pr/32071:
  Upgrade copyright year of changed file
  Remove unnecessary conversion to 'String'

Closes gh-32071
2024-01-20 14:35:19 +01:00
Stéphane Nicoll 91b980f5cb Upgrade copyright year of changed file
See gh-32071
2024-01-20 14:35:10 +01:00
mnhock d9e86dd68c Remove unnecessary conversion to 'String'
See gh-32071
2024-01-20 14:33:39 +01:00
Stéphane Nicoll 11c8b22c5a Polish 2024-01-20 14:26:48 +01:00
Sam Brannen 1a52c56bd4 Polishing 2024-01-19 19:16:41 +01:00
Sam Brannen 4cc91a2869 Ensure inherited @⁠HttpExchange annotation can be overridden in controller
This commit revises the RequestMappingHandlerMapping implementations in
Spring MVC and Spring WebFlux to ensure that a @⁠Controller class which
implements an interface annotated with @⁠HttpExchange annotations can
inherit the @⁠HttpExchange declarations from the interface or
optionally override them locally with @⁠HttpExchange or
@⁠RequestMapping annotations.

Closes gh-32065
2024-01-19 18:54:31 +01:00
Sébastien Deleuze 17cef18760 Upgrade Antora extensions versions
Sync with the versions used in the docs-build
branch.

See gh-32044
2024-01-19 18:36:43 +01:00
Juergen Hoeller 00bda65848 Polishing 2024-01-19 17:09:58 +01:00
Sam Brannen 6697461003 Reject mixed @⁠RequestMapping and @⁠HttpExchange declarations in MVC & WebFlux
This commit updates the RequestMappingHandlerMapping implementations in
Spring MVC and Spring WebFlux so that mixed @⁠RequestMapping and
@⁠HttpExchange declarations on the same element are rejected.

Note, however, that a @⁠Controller class which implements an interface
annotated with @⁠HttpExchange annotations can still inherit the
@⁠HttpExchange declarations from the interface or optionally override
them locally with @⁠HttpExchange or @⁠RequestMapping annotations.

See gh-31962
See gh-32049
Closes gh-32065
2024-01-19 16:23:42 +01:00
Arjen Poutsma c820e44a99 Unwrap request factory when creating RestClient from RestTemplate
This commit makes sure that, when building a RestClient based on the
configuration of a RestTemplate, the request factory is unwrapped if it
is a InterceptingClientHttpRequestFactory.

Closes gh-32038
2024-01-19 15:41:31 +01:00
Stéphane Nicoll 472dcdb59c Allow JPA entities to be filtered
This commit provides more control over JPA entities scanning by allowing
the result to be filtered.

Closes gh-27892
2024-01-19 15:38:53 +01:00
Sam Brannen 6691ff2072 Reject multiple @⁠HttpExchange declarations in HTTP interface clients
This commit updates HttpServiceMethod so that multiple @⁠HttpExchange
declarations on the same element (class or method) are rejected.

Closes gh-32049
2024-01-19 13:02:41 +01:00
Stéphane Nicoll 9c6e55939e Improve toString of ExponentialBackOff
Closes gh-32061
2024-01-19 12:10:36 +01:00
Stéphane Nicoll 7e511931b3 Merge pull request #32057 from erichaagdev
* pr/32057:
  Rename Gradle enterprise badge to Develocity

Closes gh-32057
2024-01-19 10:01:00 +01:00
Eric Haag 4bd898c359 Rename Gradle enterprise badge to Develocity
See gh-32057
2024-01-19 10:00:00 +01:00
rstoyanchev 1fba430dfc Update HttpExchange Javadoc to mention uses
See gh-32008
2024-01-18 18:35:28 +00:00
Sam Brannen efe85c0d70 Remove tautological ternary statement 2024-01-18 17:30:07 +01:00
Sam Brannen 2ec0c16889 Polishing 2024-01-18 17:30:07 +01:00
Stéphane Nicoll 899de4f3bf Upgrade SDK env to Java 17.0.10
See b9d366d203
2024-01-18 16:39:11 +01:00
Sam Brannen d1d9d483fe Document @⁠HttpExchange support in RequestMappingHandlerMapping 2024-01-18 16:28:40 +01:00
Arjen Poutsma 375e0e6827 Handle Content-Length in ShallowEtagHeaderFilter more robustly
This commit ensures that setting the Content-Length through
setHeader("Content-Length", x") has the same effect as calling
setContentLength in the ShallowEtagHeaderFilter. It also filters out
Content-Type headers similarly to Content-Length.

Closes gh-32039
2024-01-18 15:42:16 +01:00
Sam Brannen b8b31ff8a1 Reject multiple @⁠HttpExchange declarations in MVC and WebFlux
This commit updates the RequestMappingHandlerMapping implementations in
Spring MVC and Spring WebFlux so that multiple @⁠HttpExchange
declarations on the same element are rejected.

Closes gh-32049
2024-01-18 15:29:30 +01:00
Sam Brannen c5c77b93fe Polishing 2024-01-18 15:29:30 +01:00
Sam Brannen 6b905049eb Polishing
See gh-31962
2024-01-18 14:21:45 +01:00
Sébastien Deleuze 88a7ca0b0a Rename class-data-sharing.adoc to cds.adoc
Closes gh-32044
2024-01-18 10:16:45 +01:00
Brian Clozel e8012a64c3 Upgrade CI image to Ubuntu Jammy 20240111 2024-01-17 21:30:59 +01:00
Brian Clozel b9d366d203 Upgrade CI to JDK 17.0.10+13 21.0.2+14 and 22-ea+31 2024-01-17 21:29:50 +01:00
Stéphane Nicoll f5b0d9509d Polish 2024-01-17 18:41:15 +01:00
Sam Brannen 699da7c383 Log warning if multiple @⁠RequestMapping annotations are declared
If multiple request mapping annotations are discovered, Spring MVC and
Spring WebFlux now log a warning similar to the following (without
newlines).

Multiple @⁠RequestMapping annotations found on
void org.example.MyController.put(), but only the first will be used:
[
@⁠org.springframework.web.bind.annotation.PutMapping(consumes={}, headers={}, name="", params={}, path={"/put"}, produces={}, value={"/put"}),
@⁠org.springframework.web.bind.annotation.PostMapping(consumes={}, headers={}, name="", params={}, path={"/put"}, produces={}, value={"/put"})
]

Closes gh-31962
2024-01-17 17:46:31 +01:00
Sam Brannen 5bf74cae11 Polish documentation for @⁠RequestMapping 2024-01-17 17:46:26 +01:00
Sam Brannen 46128cb4b9 Delete duplicate content 2024-01-17 17:45:17 +01:00
Sébastien Deleuze 5dd48fc068 Mention PathPattern in functional router Javadoc
This commit makes the various supported patterns
more discoverable.

Closes gh-32045
2024-01-17 15:08:34 +01:00
Arjen Poutsma 0ada78ad84 Enable RestClient.defaultRequest
This commit enables the defaultRequest setting in the RestClient
builder.

Closes gh-32028
2024-01-17 11:23:50 +01:00
rstoyanchev 682f4715cf Polishing
See gh-30393
2024-01-17 10:15:09 +00:00
rstoyanchev c4a34fa26c Improve cancel handling in AbstractListenerReadPublisher
Closes gh-30393
2024-01-17 10:15:09 +00:00
Stéphane Nicoll e3f185a696 Upgrade to Gradle Enterprise Plugin 3.15
This reverts commit e1c8a84fec as our
version of Gradle Enterprise is not yet compatible with it.
2024-01-17 08:12:42 +01:00
Stéphane Nicoll 1b312b6f3f Polish 2024-01-16 18:45:59 +01:00
Stéphane Nicoll dc5a21fbd1 Remove outdated note
See gh-20606
2024-01-16 16:43:28 +01:00
Sam Brannen e1c8a84fec Upgrade com.gradle.enterprise plugin to 3.16.1 2024-01-16 15:58:22 +01:00
Sam Brannen 410fe409d2 Upgrade io.spring.ge.conventions plugin to 0.0.15 2024-01-16 15:55:30 +01:00
Stéphane Nicoll e0c5068d0b Fix incorrect assertions using json path
Closes gh-32036
2024-01-16 10:59:43 +01:00
Stéphane Nicoll faba044735 Polish JsonPathExpectationsHelperTests 2024-01-15 17:04:11 +01:00
Stéphane Nicoll 4d885f9aad Polish 2024-01-15 16:45:53 +01:00
Sam Brannen fdf187ec46 Polishing 2024-01-15 15:45:33 +01:00
Stéphane Nicoll 0c42965fc3 Polish 2024-01-15 11:17:19 +01:00
Sam Brannen e1236a8672 Polishing 2024-01-14 16:00:50 +01:00
Sam Brannen 7daff59cb1 Fix alias resolution error message in SimpleAliasRegistry
Prior to this commit, the alias resolution error message in
SimpleAliasRegistry was misleading.

When a resolution conflict is detected, the IllegalStateException
thrown by resolveAliases(...) now states that the resolved alias is
already registered for an `existingName` instead of the `registeredName`.

See gh-31353
Closes gh-32025
2024-01-14 15:19:18 +01:00
Sam Brannen 5d309d5724 Improve SimpleAliasRegistryTests
This commit improves SimpleAliasRegistryTests in the following ways.

- Some existing methods have been split up into smaller test methods
  which focus on a single use case.

- The use of Mockito mocks has been replaced by a hand-crafted
  StubStringValueResolver which ensures that existing aliases and names
  are not accidentally replaced by null thereby removing their removing
  there mappings inadvertently.

- Several test methods now include inline comments that document the
  current state of the aliasMap in order to clarify what is happening
  behind the scenes in the ConcurrentHashMap.

- Several test methods warn that the current expectations are based on
  ConcurrentHashMap iteration order!

- New @⁠ParameterizedTest which is currently @⁠Disabled but
  demonstrates that complex use cases involving placeholder replacement
  can be supported consistently -- regardless of the values of the
  aliases involved -- but only if alias registration order is honored.

Closes gh-31353
2024-01-14 14:22:02 +01:00
Sam Brannen eeb145ee0b Fix link to global appendix 2024-01-13 14:52:57 +01:00
Sam Brannen 9f5cda958e Enable table striping by default in the reference manual
Closes gh-32022
2024-01-13 14:50:16 +01:00
rstoyanchev 47779d6a53 Double-checked lock in ChannelSendOperator#request
Closes gh-31865
2024-01-12 17:15:47 +00:00
Stéphane Nicoll 2a43cc7574 Polish 2024-01-12 17:21:21 +01:00
Sam Brannen c4831d2586 Document that Conditions can be ordered
Closes gh-32019
2024-01-12 16:30:24 +01:00
Sam Brannen e4569defd9 Polish Javadoc for Condition 2024-01-12 16:24:20 +01:00
rstoyanchev 65cb59517d Polishing contribution
Closes gh-32008
2024-01-12 15:15:59 +00:00
Olga MaciaszekSharma b729008f4d Improve docs on server use of @HttpExchange
See gh-32008
2024-01-12 15:15:59 +00:00
Stéphane Nicoll 122d8b9e4e Polish 2024-01-12 14:55:21 +01:00
Arjen Poutsma b16f379788 Improve RestTemplate Javadoc
See gh-32016
2024-01-12 12:52:19 +01:00
Yanming Zhou c868bc554f Refine Kotlin internal modifier impact documentation
This commit is a refinement of 01b2856114.

Closes gh-32010
2024-01-12 12:34:19 +01:00
Sébastien Deleuze 5c77c3739e Find destroy methods in superclass interfaces
Related tests will be added in
https://github.com/spring-projects/spring-aot-smoke-tests.

Closes gh-32006
2024-01-12 11:37:42 +01:00
Stéphane Nicoll ee04442be7 Polish 2024-01-12 09:20:09 +01:00
Stéphane Nicoll f067ff862b Merge pull request #32015 from wfouche
* pr/32015:
  Upgrade to JMH 1.37

Closes gh-32015
2024-01-12 08:43:02 +01:00
Werner Fouché 68864674cc Upgrade to JMH 1.37
See gh-32015
2024-01-12 08:40:47 +01:00
Stéphane Nicoll f1a335708a Polish 2024-01-11 14:05:37 +01:00
Spring Builds d786635239 Next development version (v6.1.4-SNAPSHOT) 2024-01-11 09:11:17 +00:00
rstoyanchev 50fad9ed05 Lenient port handling in HierarchicalUriComponents#toUriString
Closes gh-32003
2024-01-10 20:59:59 +00:00
rstoyanchev 2b4ffe0391 Consistent inclusion of baseUrl in URI_TEMPLATE attribute
Closes gh-31882
2024-01-10 20:39:14 +00:00
rstoyanchev e7eaaaded1 Explicit initialization of shouldValidate flags
Closes gh-32007
2024-01-10 18:13:25 +00:00
Sam Brannen f6e52900a2 Polish SpEL documentation 2024-01-10 17:39:19 +01:00
Sam Brannen 62b5e42769 Fix syntax for disabled selection/projection tests in ParsingTests 2024-01-10 17:39:19 +01:00
Sébastien Deleuze 1631be5660 Provide guidelines in AspectJ documentation to avoid dumps
Closes gh-27650
2024-01-10 17:08:56 +01:00
Juergen Hoeller 9ccc72a9fb Upgrade to spring-javaformat-checkstyle 0.0.41 2024-01-10 17:07:01 +01:00
Sébastien Deleuze 01b2856114 Document Kotlin internal modifier impact on @Bean
Closes gh-31985
2024-01-10 13:41:46 +01:00
rstoyanchev 6dca7b28cc Polishing contribution
Closes gh-31991
2024-01-10 12:17:20 +00:00
Olga MaciaszekSharma 864b1c95cd Document exception handling for RestClient and RestTemplate-backed interface clients. 2024-01-10 12:17:20 +00:00
rstoyanchev 168c60c18a Polishing contribution
Closes gh-31992
2024-01-10 12:17:20 +00:00
Aaron Rosser 1e49334209 Exclude query from URI in WebClient checkpoints
See gh-31992
2024-01-10 12:17:20 +00:00
Juergen Hoeller 79cc0ec4aa Make prepareSynchronization overridable again
Closes gh-32000
2024-01-10 13:07:20 +01:00
Juergen Hoeller fdfa4284de Upgrade to Reactor 2023.0.2 and Micrometer 1.12.2
Includes SLF4J 2.0.11, Tomcat 10.1.18, Apache HttpClient 5.3, POI 5.2.5, OpenPDF 1.3.36

Closes gh-31995
Closes gh-31996
2024-01-10 10:48:12 +01:00
Arjen Poutsma 49d3ec58fc Use timeout for JdkClientHttpRequest response retrieval
This commit ensures that, in JdkClientHttpRequest, the response is
obtained  using a timeout, instead of blocking indefinitely.

Closes gh-31911
2024-01-10 09:53:16 +01:00
Stéphane Nicoll c4405104a8 Polish 2024-01-09 17:31:34 +01:00
Sam Brannen 4b0443090a Polish Javadoc for test annotations 2024-01-09 16:32:22 +01:00
Sam Brannen b1bf1b0c82 Update Spring Properties section of reference manual
This commit documents the following Spring properties in the reference
manual.

- spring.aot.enabled
- spring.cache.reactivestreams.ignore
- spring.classformat.ignore
- spring.context.checkpoint
- spring.context.exit

Closes gh-31987
2024-01-09 14:23:14 +01:00
Sam Brannen 5d45b94e93 Polishing 2024-01-09 14:23:14 +01:00
Sébastien Deleuze 598c972a78 Update ContentRequestMatchers#multipartData Javadoc
This commit updates ContentRequestMatchers#multipartData
Javadoc to mention Tomcat fork of Commons FileUpload library
instead of the original variant.

It also adds a similar note to
ContentRequestMatchers#multipartDataContains.

Closes gh-31988
2024-01-09 14:12:09 +01:00
rstoyanchev 2593b60f2b Do not set exception attribute if response body is set
ResponseEntityExceptionHandler should not set the exception attribute
when there is a response body, and the response is fully handled.

Closes gh-31541
2024-01-09 12:11:23 +00:00
Arjen Poutsma e6f638132c Create case-insensitive copy in RestClientResponseException
Closes gh-31978
2024-01-09 12:11:02 +01:00
Sam Brannen b823c46aae Revise SpEL Evaluation documentation 2024-01-09 12:03:28 +01:00
Juergen Hoeller 4d11307b84 Polishing 2024-01-09 11:55:04 +01:00
Juergen Hoeller 03b6e51225 Evaluate thread-bound MethodInvocation only if it matches current Method
Closes gh-26068
2024-01-09 11:54:05 +01:00
Sam Brannen 785598629a Make max length of SpEL expressions in an ApplicationContext configurable
This commit introduces support for a Spring property named
`spring.context.expression.maxLength`. When set, the value of that
property is used internally in StandardBeanExpressionResolver to
configure the SpelParserConfiguration used when evaluating String
values in bean definitions, @⁠Value, etc.

Closes gh-31952
2024-01-09 11:15:32 +01:00
Arjen Poutsma 3452354a11 Ensure correct capacity in DefaultDataBuffer
Closes gh-31873
2024-01-09 10:33:46 +01:00
Juergen Hoeller bb1cdb6b48 Consistently expose parameter annotations from base classes as well
Closes gh-25788
2024-01-08 21:03:32 +01:00
rstoyanchev 37fa82c578 Lenient rejectedValue lookup in SpringValidatorAdapter
Closes gh-29043
2024-01-08 16:39:53 +00:00
Stéphane Nicoll 1f2d29ee08 Polish 2024-01-08 17:12:33 +01:00
Sébastien Deleuze cffc8835c6 Mention parameter-names in Jackson2ObjectMapperBuilder documentation
Closes gh-31959
2024-01-08 14:59:02 +01:00
Stéphane Nicoll 515c654a46 Merge pull request #31976 from wfouche
* pr/31976:
  Upgrade to gradle-versions-plugin 0.50.0

Closes gh-31976
2024-01-08 13:04:06 +01:00
Werner Fouché aacb7e1604 Upgrade to gradle-versions-plugin 0.50.0
See gh-31976
2024-01-08 13:03:27 +01:00
Stéphane Nicoll c86642dfee Merge pull request #31977 from SuhasBk
* pr/31977:
  Add missing preposition

Closes gh-31977
2024-01-08 13:01:31 +01:00
Suhas Kowligi f4a9b12340 Add missing preposition
See gh-31977
2024-01-08 13:00:13 +01:00
Sébastien Deleuze bd66763f26 Polishing
See gh-28546
2024-01-08 12:27:37 +01:00
Stéphane Nicoll 2d3b02a89d Polish 2024-01-08 11:48:08 +01:00
rstoyanchev 8552e149b5 Improve method validation for container elements
This change moves container element properties from ParameterErrors
to base class ParameterValidationResult, and makes that support
independent of whether violations are nested within a container
element bean or through constraints on container elements, e.g.
`List<@NotBlank String>`.

Closes gh-31887
2024-01-05 16:32:14 +00:00
rstoyanchev e0d6b69195 Update contribution
Closes gh-30300
2024-01-04 14:53:13 +00:00
Yanming Zhou a3532bfccc ResponseStatusException reason as message code for ProblemDetail
See gh-30300
2023-04-06 17:18:27 +08:00
Werner Fouché 6697f01d05 Upgrade to Kotlin 1.9.22
Closes gh-31971
2024-01-08 09:28:16 +01:00
Stéphane Nicoll 01c62f86b3 Polish 2024-01-07 17:33:27 +01:00
Juergen Hoeller 9912a52bb8 Avoid getMostSpecificMethod resolution for non-annotated methods
This is aligned with AutowiredAnnotationBeanPostProcessor now.

Closes gh-31967
2024-01-07 16:33:49 +01:00
Juergen Hoeller 419e34e571 Introduce getMostSpecificMethod variant on BridgeMethodResolver
This is able to resolve the original method even if no bridge method has been generated at the same class hierarchy level (a known difference between the Eclipse compiler and regular javac).

Closes gh-21843
2024-01-07 16:33:06 +01:00
Werner Fouché f0e16bd31b Update SDKMAN config to use 17.0.9-librca
Closes gh-31966
2024-01-07 15:05:19 +01:00
Juergen Hoeller 43107e7eb1 Propagate arguments for dynamic prototype-scoped advice
Closes gh-28407
2024-01-07 00:12:15 +01:00
Juergen Hoeller 81bd6be1c0 Upgrade to Checkstyle 10.12.7 2024-01-06 23:37:45 +01:00
Juergen Hoeller d6c84c43ec Polishing 2024-01-06 23:24:48 +01:00
Juergen Hoeller 70247c4a94 Refine exception handling for type not present versus access exception
Includes TypeVariable bypass for reflection-free annotation retrieval.
Includes info log message for annotation attribute retrieval failure.

Closes gh-27182
2024-01-06 23:02:59 +01:00
Stéphane Nicoll 87b35e7d8e Polish 2024-01-06 09:21:16 +01:00
slovenlyimp a51c22b266 Fix a typo in kotlin.adoc
Closes gh-31958
2024-01-05 20:26:04 +01:00
Sébastien Deleuze 318d460256 Add CORS support for Private Network Access
This commit adds CORS support for Private Network Access
by adding an Access-Control-Allow-Private-Network response
header when the preflight request is sent with an
Access-Control-Request-Private-Network header and that
Private Network Access has been enabled in the CORS
configuration.

See https://developer.chrome.com/blog/private-network-access-preflight/
for more details.

Closes gh-28546
2024-01-05 20:07:51 +01:00
Stéphane Nicoll d7cfdc633a Polish 2024-01-05 18:42:44 +01:00
Sam Brannen 085af10afd Polishing 2024-01-05 18:16:39 +01:00
Stéphane Nicoll a8273a3009 Resolve property placeholder in RequestMapping if necessary
This commit makes sure to resolve placeholders in request mappings
using the EmbeddedValueResolver of the current WebApplicationContext.

To avoid retrieving the context too often, we check for the presence of
the standard placeholder prefix.

Closes gh-26795
2024-01-05 17:50:54 +01:00
Sam Brannen 580d9f81e2 Polishing 2024-01-05 17:06:32 +01:00
Sam Brannen 79b0d71514 Support the use of @⁠Resource in test classes in AOT mode
Closes gh-31733
2024-01-05 16:31:18 +01:00
Sam Brannen f6b36a689a Introduce processInjection() in CommonAnnotationBeanPostProcessor
To align with the existing processInjection() method in
AutowiredAnnotationBeanPostProcessor, this commit introduces an analogous
method in CommonAnnotationBeanPostProcessor.

Closes gh-31956
2024-01-05 16:05:07 +01:00
Sam Brannen 4b6126c057 Polishing 2024-01-05 15:17:51 +01:00
Fabrice Bibonne a108e701bc Add Javadoc for use of regexp PathPattern
Closes gh-31886
2024-01-05 14:47:45 +01:00
Johnny Lim 0ad561d379 Ensure that Observation is stopped and scope is closed in doReceiveAndExecute()
Closes gh-31798
2024-01-05 14:45:58 +01:00
Brian Clozel 1372265bd9 Undo workaround for SameSite support in WebFlux
This commit implements Cookie support in WebFlux without any workaround
as now all supported servers have the SameSite feature enabled.

Closes gh-31954
2024-01-05 14:44:32 +01:00
Sam Brannen 476ef0c3ca Introduce basic unit test for AutowiredAnnotationBeanPostProcessor.processInjection() 2024-01-05 13:22:29 +01:00
Stéphane Nicoll 534d3229fe Polish 2024-01-05 10:46:00 +01:00
Juergen Hoeller 07097976ef Polishing 2024-01-05 10:08:57 +01:00
Juergen Hoeller fb4fbeab50 Allow CronTrigger to resume from specified timestamp
Includes differentiation between lenient and fixed execution.
Includes default time zone resolution from scheduler-wide Clock.

Closes gh-19475
Closes gh-31948
2024-01-05 10:08:01 +01:00
Stéphane Nicoll b169dc50ad Upgrade CI to Ubuntu Jammy 20231211.1 2024-01-05 09:41:45 +01:00
Stéphane Nicoll 02e32baa80 Merge pull request #31951 from pri88yank
* pr/31951:
  Polish "Fix references to "application/*+xml" in Javadoc"
  Fix references to "application/*+xml" in Javadoc

Closes gh-31951
2024-01-05 06:45:19 +01:00
Stéphane Nicoll 549f6c1e80 Polish "Fix references to "application/*+xml" in Javadoc"
See gh-31951
2024-01-05 06:44:14 +01:00
pri88yank 16b4c25f7d Fix references to "application/*+xml" in Javadoc
See gh-31951
2024-01-05 06:44:02 +01:00
Stéphane Nicoll af2e13e211 Polish 2024-01-05 06:34:09 +01:00
Brian Clozel 7c9307e970 Fix HandlerMappingIntrospector uri matching
Prior to this commit, the `HandlerMappingIntrospector` would comparea
request with a cached request by using `String#matches` on their String
URI. This could lead to `PatternSyntaxException` exceptions at runtime
if the request URI contained pattern characters.

This commit fixes this typo to use `String#equals` instead.

Fixes gh-31937
2024-01-04 16:44:00 +01:00
Stéphane Nicoll 4f599b7396 Polish 2024-01-04 14:49:45 +01:00
Stéphane Nicoll 2784f6008e Only log status in ServletRequestHandledEvent
This commit updates the description of RequestHandledEvent to avoid
providing a misleading status as the absence of a failure logs OK which
can be inaccurate.

Closes gh-27595
2024-01-04 11:47:59 +01:00
Stefano Cordio be9ee9112c Upgrade to AssertJ 3.25.1, use AssertJ BOM
Closes gh-31945
2024-01-04 09:55:12 +01:00
Sébastien Deleuze 19a87e968e Update outdated elements in Kotlin reference documentation
Closes gh-31943
2024-01-03 18:39:15 +01:00
Sébastien Deleuze 207b9a14f4 Improve the documentation and discoverability of CoWebFilter
Closes gh-31877
2024-01-03 17:50:22 +01:00
Stéphane Nicoll 05ebca8677 Polish 2024-01-03 17:03:58 +01:00
Brian Clozel f846d9484c Add Javadoc to MockHttpServletResponse
This commit adds Javadoc to the `getContentLength` method of
`MockHttpServletResponse` to reflect that it gets its value from the
HTTP response header.

Closes gh-31833
2024-01-03 15:19:53 +01:00
Dávid Csákvári 50069ef029 Update autowired-qualifiers.adoc 2024-01-03 14:56:51 +01:00
Stéphane Nicoll 777ff3f1a8 Merge pull request #31938 from JuHyun419
* pr/31938:
  Fix typo in NumberFormat javadoc

Closes gh-31938
2024-01-03 14:27:56 +01:00
juhyun 89466cb33c Fix typo in NumberFormat javadoc
See gh-31938
2024-01-03 14:27:00 +01:00
Stéphane Nicoll bf3a478990 Add support for functional registration of application listener
This commit adds a functional style registration of an application
listener for a particular event. Rather than introducing another method
at the ConfigurableApplicationContext interface level, this commit
provides a factory method in GenericApplicationListener.

Closes gh-21411
2024-01-03 13:38:08 +01:00
Stéphane Nicoll efb97cca82 Merge pull request #31932 from janjouketjalsma
* pr/31932:
  Fix Kotlin example for simpler SELECT variant using IN

Closes gh-31932
2024-01-02 18:12:08 +01:00
Jan Jouke Tjalsma b692c0ed03 Fix Kotlin example for simpler SELECT variant using IN
Removed unused code, fixed bind parameter name.

See gh-31932
2024-01-02 18:10:36 +01:00
Sam Brannen 6eed2b0aee Upgrade to "TestNG Engine for the JUnit Platform" version 1.0.5
Thanks to a bug fix in 1.0.5, test methods in TestNG test classes can
finally be package private as was always the case with TestNG itself.

See https://github.com/junit-team/testng-engine/issues/16
2024-01-02 16:46:24 +01:00
Sam Brannen 7876db03c6 Upgrade to TestNG 7.9.0 2024-01-02 16:45:04 +01:00
Sam Brannen ffddbb586e Upgrade to AssertJ 3.25.0 2024-01-02 16:45:04 +01:00
Sam Brannen a3c11fc033 Clean up warnings in tests in Gradle build 2024-01-02 16:44:52 +01:00
Stéphane Nicoll 321de9ab9b Update copyright year to 2024 2024-01-02 16:22:43 +01:00
Brian Clozel ec5f566ba5 Fix Scheduled observation convention for lambdas
Prior to this commit, the `DefaultScheduledTaskObservationConvention`
would fail as it tried to add a `KeyValue` to the observation context
that is `null`. This is rejected by the observation registry and should
be prevented. This happened when registered scheduled methods were
lambdas or part of anonymous classes. Those types do not have a
canonical name and return `null` as a value there.

This commit ensures that for these cases, the default convetion uses a
`"ANONYMOUS"` value as the `"code.namespace"` keyvalue.

Fixes gh-31918
2024-01-02 15:12:26 +01:00
Stéphane Nicoll 2d6b77336b Revert Upgrad to Jetty Reactive Httpclient 4.0.2
Upgrading leads to to WebClientIntegrationTests to fail with Jetty and
the build does not complete properly. This commit reverts the upgrade.

See gh-31931
2024-01-01 11:22:25 +01:00
Stéphane Nicoll 9a1ee48d73 Merge pull request #31930 from izeye
* pr/31930:
  Update copyright year of changed files
  Polish

Closes gh-31930
2024-01-01 11:01:07 +01:00
Stéphane Nicoll e22d1efdc0 Update copyright year of changed files
See gh-31930
2024-01-01 11:00:56 +01:00
Johnny Lim ff8097d37c Polish
See gh-31930
2024-01-01 10:59:35 +01:00
Stéphane Nicoll 7d44a4dcad Polish 2024-01-01 10:56:33 +01:00
Juergen Hoeller fdb454b9a4 Declare JdkDynamicAopProxy's ProxiedInterfacesCache as private
See gh-30499
2023-12-31 13:48:50 +01:00
Juergen Hoeller b4174377c2 Correctly document Propagation.NOT_SUPPORTED in javadoc
See gh-31907
2023-12-31 13:44:09 +01:00
Juergen Hoeller 174eae377f Upgrade to ASM master (including early support for Java 23 bytecode)
Closes gh-31929
2023-12-31 13:29:50 +01:00
Juergen Hoeller 243ec88e95 Upgrade to SLF4J 2.0.10, AspectJ 1.9.21, Groovy 4.0.17, Tomcat 10.1.17, Jetty 12.0.5, Netty 4.1.104, Jackson 2.15.3, Protobuf 3.25.1, OpenPDF 1.3.35 2023-12-30 16:47:50 +01:00
Stéphane Nicoll 9f3fd103ef Polish 2023-12-30 11:17:49 +01:00
Juergen Hoeller 0ad3800f54 Polishing 2023-12-30 11:06:16 +01:00
Juergen Hoeller 473efb6d4f Adapt test to current 5.0+ behavior
See gh-24502
2023-12-30 10:47:52 +01:00
Stéphane Nicoll 153f8895cb Polish 2023-12-29 18:19:26 +01:00
Juergen Hoeller f5b4f7d9e8 Support for SSLContext configuration on StandardWebSocketClient
Closes gh-30680
2023-12-28 23:42:04 +01:00
Juergen Hoeller 989625d2d4 Allow SockJsUrlInfo to be overridden in SockJsClient
Closes gh-25888
2023-12-28 20:56:18 +01:00
Stéphane Nicoll 28e5468162 Merge pull request #31917 from ghkim3221
* pr/31917:
  Polish "Fix usage of WebClientAdapter in reference documentation"
  Fix usage of WebClientAdapter in reference documentation

Closes gh-31917
2023-12-28 13:53:53 +01:00
Stéphane Nicoll b1c0b65666 Polish "Fix usage of WebClientAdapter in reference documentation"
See gh-31917
2023-12-28 13:52:57 +01:00
Gihwan Kim 490aaa1ed8 Fix usage of WebClientAdapter in reference documentation
See gh-31917
2023-12-28 13:51:12 +01:00
Stéphane Nicoll c7d2d6716d Merge pull request #31916 from quaff
* pr/31916:
  Upgrade copyright year of changed files
  Polish "Replace if with switch where feasible"
  Replace if with switch where feasible
  Use Map.computeIfAbsent() where feasible
  Polish "Use Object.equals() where feasible"
  Use Object.equals() where feasible
  Polish "Use diamond operator where feasible"
  Use diamond operator where feasible
  Use auto boxing and unboxing where feasible
  Use enhanced for loop where feasible
  Polish "Use text block where feasible"
  Use text block where feasible
  Polish "Use String.repeat() where feasible"
  Use String.repeat() where feasible
  Polish "Remove unnecessary final modifier"
  Remove unnecessary final modifier

Closes gh-31916
2023-12-28 13:47:08 +01:00
Stéphane Nicoll eefe65d95a Upgrade copyright year of changed files
See gh-31916
2023-12-28 13:36:58 +01:00
Stéphane Nicoll 3c5d46166e Polish "Replace if with switch where feasible"
See gh-31916
2023-12-28 13:33:32 +01:00
Yanming Zhou cfa3aa001f Replace if with switch where feasible
See gh-31916
2023-12-28 13:29:50 +01:00
Yanming Zhou ea5ef098cf Use Map.computeIfAbsent() where feasible
See gh-31916
2023-12-28 13:23:48 +01:00
Stéphane Nicoll adcf236a3d Polish "Use Object.equals() where feasible"
See gh-31916
2023-12-28 13:21:46 +01:00
Yanming Zhou 72a9864788 Use Object.equals() where feasible
See gh-31916
2023-12-28 13:19:03 +01:00
Stéphane Nicoll a6e87b40c7 Polish "Use diamond operator where feasible"
See gh-31916
2023-12-28 13:14:26 +01:00
Yanming Zhou 094479b55f Use diamond operator where feasible
See gh-31916
2023-12-28 13:08:08 +01:00
Yanming Zhou db2c532c07 Use auto boxing and unboxing where feasible
See gh-31916
2023-12-28 13:01:44 +01:00
Yanming Zhou 4a450c6fab Use enhanced for loop where feasible
See gh-31916
2023-12-28 13:01:44 +01:00
Stéphane Nicoll ed1bfb8177 Polish "Use text block where feasible"
See gh-31916
2023-12-28 13:01:44 +01:00
Yanming Zhou a35384fd57 Use text block where feasible
See gh-31916
2023-12-28 13:01:44 +01:00
Stéphane Nicoll 9d31537ae5 Polish "Use String.repeat() where feasible"
See gh-31916
2023-12-28 13:01:44 +01:00
Yanming Zhou dee1b726f9 Use String.repeat() where feasible
See gh-31916
2023-12-28 13:01:44 +01:00
Stéphane Nicoll 7cfff4049d Polish "Remove unnecessary final modifier"
See gh-31916
2023-12-28 13:01:44 +01:00
Yanming Zhou 45080e3724 Remove unnecessary final modifier
final is useless for private and static methods

See gh-31916
2023-12-28 13:01:43 +01:00
Stéphane Nicoll c3b5f5bf90 Merge pull request #31913 from quaff
* pr/31913:
  Update copyright year of changed files
  Cleanup kotlin sources

Closes gh-31913
2023-12-28 11:56:12 +01:00
Stéphane Nicoll 7e5afc8bbb Update copyright year of changed files
See gh-31913
2023-12-28 11:47:17 +01:00
Yanming Zhou 7474af4f09 Cleanup kotlin sources
1. remove unused import
2. remove redundant semicolon
3. remove redundant empty constructor and SAM-constructor
4. remove unnecessary type argument
5. adjust indent

See gh-31913
2023-12-28 11:46:47 +01:00
Stéphane Nicoll 28a7b6103a Merge pull request #31914 from quaff
* pr/31914:
  Add missing @Test
  Fix @Nested class not be executed

Closes gh-31914
2023-12-28 11:40:56 +01:00
Yanming Zhou 3cddb0434d Add missing @Test
See gh-31914
2023-12-28 11:38:03 +01:00
Yanming Zhou 36a72115f9 Fix @Nested class not be executed
See gh-31914
2023-12-28 11:37:47 +01:00
Stéphane Nicoll 3c0b5459be Merge pull request #31912 from izeye
* pr/31912:
  Add Javadoc since to CacheOperationContext.getGeneratedKey()

Closes gh-31912
2023-12-28 11:29:31 +01:00
Johnny Lim 088be2d017 Add Javadoc since to CacheOperationContext.getGeneratedKey()
See gh-31912
2023-12-28 11:25:36 +01:00
Juergen Hoeller a155a6b3e2 Document target method expectations for ReactiveTransactionManager
Closes gh-23277
2023-12-27 23:48:55 +01:00
Juergen Hoeller a338a16b29 Polishing 2023-12-27 23:23:38 +01:00
Juergen Hoeller 7613bdfdf9 Document thread safety and visibility for Spring-managed bean instances
Closes gh-8986
2023-12-27 23:22:35 +01:00
Juergen Hoeller 57f27fa42f Document autowiring of request/session proxies into Spring-managed beans
Closes gh-26201
2023-12-27 23:22:30 +01:00
Juergen Hoeller 55d9d151fb Recommend ResourcePropertySource for distinct PropertySource names
Closes gh-28886
2023-12-27 23:19:27 +01:00
Stéphane Nicoll 70f31dee45 Polish 2023-12-27 13:04:21 +01:00
Stéphane Nicoll 699f93fed7 Use proper SQLServer dialect for Hibernate 6+
This commit fixes the Hibernate dialect lookup for SQLServer as it was
previously using a dialect that has been deprecated. In recent
versions, the standard SQLServerDialect is the one we should be using.

Closes gh-31896
2023-12-26 14:03:20 +01:00
Kai Zander 4c6ca05af5 Fix formatting in scheduling.adoc 2023-12-26 11:36:51 +01:00
Juergen Hoeller 75c7596259 Allow Propagation.NOT_SUPPORTED with @TransactionalEventListener
Closes gh-31907
2023-12-26 10:59:19 +01:00
Juergen Hoeller 17d362fa85 Document limited concurrency with fixed-delay tasks on virtual threads
Closes gh-31900
2023-12-26 10:59:13 +01:00
Juergen Hoeller a428955438 Avoid unnecessary DatabasePopulator init/destroy processing
Closes gh-23405
2023-12-23 13:40:12 +01:00
Brian Clozel 4afac17e58 Reject invalid forwarded requests in ForwardedHeaderFilter
Prior to this commit, the `ForwardedHeaderFilter` and the forwarded
header utils would throw `IllegalArgumentException` and
`IllegalStateException` when request headers are invalid and cannot be
parsed for Forwarded handling.

This commit aligns the behavior with the WebFlux counterpart by
rejecting such requests with HTTP 400 responses directly.

Fixes gh-31842
2023-12-22 17:27:06 +01:00
Sébastien Deleuze 8bd8c4f627 Add support for @Async Kotlin function returning Unit?
Closes gh-31881
2023-12-22 15:33:34 +01:00
Stéphane Nicoll 0390709577 Use proper Oracle dialect for Hibernate 6+
This commit fixes the Hibernate dialect lookup for Oracle as it was
previously using a dialect that has been moved and deprecated to a
separate project. In recent versions, the standard OracleDialect is the
one we should be using.

Closes gh-31892
2023-12-22 15:22:01 +01:00
Stéphane Nicoll 9f2970bc5c Use non deprecated MySQL dialect for Hibernate 6+
This commit fixes the Hibernate dialect lookup for MySQL as it was
previously using a deprecated dialect that has been removed in the most
recent Hibernate version.

Closes gh-31889
2023-12-22 15:03:40 +01:00
Juergen Hoeller 232225b2aa Polishing 2023-12-22 13:06:29 +01:00
Stéphane Nicoll 5caf714ff4 Document CGLIB restriction with methods that are effectively private
Closes gh-28973
2023-12-22 12:39:35 +01:00
Juergen Hoeller cd11219fa7 Declare proxyMetadataCache as volatile and ProxiedInterfacesCache fields as final
See gh-30499
2023-12-22 12:27:03 +01:00
Juergen Hoeller 44c652ec98 Introduce ProxiedInterfacesCache for JdkDynamicAopProxy
Closes gh-30499
2023-12-22 11:55:59 +01:00
Stéphane Nicoll cd8bc2f82a Remove useless empty inheritDoc Javadoc tag 2023-12-22 11:23:11 +01:00
Stéphane Nicoll 12f6330fae Improve code coverage of PropertyPlaceholderHelper
See gh-26268
2023-12-22 11:07:16 +01:00
Juergen Hoeller fc0ea465e1 Clarify expectations for getBean call with provided arguments
Closes gh-24955
2023-12-21 19:32:38 +01:00
rstoyanchev 459338f6fd Unwrap Optional in MethodValidationAdapter
See gh-31746
2023-12-21 17:55:49 +00:00
rstoyanchev f0add920f5 Adjust container types to which methodValidation
After the updates to MethodValidationAdapter in commit d7ce13 related
to method validation on element containers, we also need to adjust
the checks in HandlerMethod when method validation applies.

See gh-31746
2023-12-21 17:50:40 +00:00
rstoyanchev 33c149077a Check constraints on container elements
We now check for constraint annotations on elements of a
container to decide whether to apply method validation.

Closes gh-31870
2023-12-21 17:35:19 +00:00
Baoyi Chen e00a882333 Complete Jetty frame callback when opcode is not PONG
The onWebSocketFrame method should complete callback.
For more details, see https://github.com/jetty/jetty.project/issues/11088.

Closes gh-31869
2023-12-21 17:56:26 +01:00
Sam Brannen 3ed5a90b7c Fix assertions in ReactiveCachingTests 2023-12-21 17:30:56 +01:00
Sam Brannen 3476402a75 Polish switch statements 2023-12-21 17:30:56 +01:00
Juergen Hoeller b04803de99 Polishing 2023-12-21 17:20:29 +01:00
Juergen Hoeller f443cf965a Introduce NoOpTaskScheduler for test setups
Closes gh-28073
2023-12-21 17:20:24 +01:00
Stéphane Nicoll c9292f8e09 Replace Twitter reference to 𝕏 2023-12-21 15:56:20 +01:00
Juergen Hoeller bd65a19d71 Introduce write method fallback step for overloaded setter methods
Closes gh-31872
2023-12-21 14:32:10 +01:00
Sébastien Deleuze 85cb6cc5fb Support Kotlin extensions in web handlers
This commit restores support for Kotlin extensions in
web handlers, and adds support for invoking reflectively
suspending extension functions, as well as the other
features supported as of Spring Framework 6.1 like
value classes and default value for parameters.

Closes gh-31876
2023-12-21 12:16:33 +01:00
Juergen Hoeller 5f8a031c22 Introduce "spring.cache.reactivestreams.ignore" escape hatch
Closes gh-31861
2023-12-21 11:14:33 +01:00
Juergen Hoeller dc564f3ef2 Respect cache hit when empty Mono/Flux response is returned
Closes gh-31868
2023-12-20 22:52:51 +01:00
rstoyanchev d7ce13c763 Revert use of leafBean in MethodValidationAdapter
The goal for #31530 was to support bean validation on Set and other
method parameters that are containers of value(s) for which there is
a registered Jakarta Validation ValueExtractor.

Unfortunately, bean validation does not expose the unwrapped value
for a Path.Node, which we need for a method parameter in order to
create a BindingResult for the specific bean within the container,
and the leafBean that we tried to use is really the node at the
very bottom of the property path (i.e. not what we need).

This change removes the use of beanLeaf, restores the logic as it
was before, adds support for arrays, and a new test class for
scenarios with cascaded violations.

See gh-31746
2023-12-20 17:56:05 +00:00
Stéphane Nicoll 7b9037b054 Merge pull request #31875 from izeye
* pr/31875:
  Polish Javadoc for ClientRequestObservationContext constructors

Closes gh-31875
2023-12-20 17:29:45 +01:00
Johnny Lim 3162afbf16 Polish Javadoc for ClientRequestObservationContext constructors
See gh-31875
2023-12-20 17:26:29 +01:00
Stéphane Nicoll 1bd523f6b6 Polish 2023-12-20 09:52:55 +01:00
Juergen Hoeller 4c0d0ba5b3 Use standard String comparison in PropertyDescriptorComparator
Closes gh-31866
2023-12-20 08:45:53 +01:00
Stéphane Nicoll 212346a86d Polish 2023-12-19 19:48:42 +01:00
Brian Clozel 564803f56a Trigger JDK 22 builds every morning in CI
Closes gh-31459
2023-12-19 18:39:23 +01:00
Brian Clozel df708d16e4 Add missing JDK env variable in CI script 2023-12-19 18:23:22 +01:00
Brian Clozel 848dedb576 Upgrade CI to JDK 22ea28 2023-12-19 18:08:36 +01:00
Brian Clozel 4516e0d413 Ignore XML tests on JDK 22
This is until https://bugs.openjdk.org/browse/JDK-8322216 is resolved.

See gh-31459
2023-12-19 18:06:47 +01:00
Juergen Hoeller a23375c49d Document JDBC driver requirement for KeyHolder-based update methods
Closes gh-31486
2023-12-19 17:53:32 +01:00
Brian Clozel 53b937976d Reject setups with multiple observation conventions
Prior to this commit, the `WebHttpHandlerBuilder` would only configure
a custom observation convention if there is a single convention in the
application context. It would other wise use the default.

This commit aligns with the previous Spring Boot behavior where multiple
conventions setups are rejected as invalid with
`NoUniqueBeanDefinitionException`.

Fixes gh-31864
2023-12-19 17:35:02 +01:00
Sébastien Deleuze 12f01f9b5f Add support for @RequestMapping on Kotlin property accessors
This commit refines InvocableHandlerMethod (both Servlet and
Reactive variants) in order to support annotated property
accessors as they translate into regular Java methods, instead
of throwing a NullPointerException.

Closes gh-31856
2023-12-19 12:29:55 +01:00
Sébastien Deleuze 917978cbc2 Refactor InvocableHandlerMethodKotlinTests
The variant in org.springframework.web.method.support in
order to allow testing with a various classes.

See gh-31856
2023-12-19 12:10:13 +01:00
rstoyanchev 3f5c3b1747 Fix checkstyle violation
See gh-31711
2023-12-18 15:32:18 +00:00
rstoyanchev bec7210b4b Improve check to skip bean validation in DataBinder
DataBinder should skip any jakarta.validation.Validator yielding
to method validation when that is expected. This change improves
the check to skip by unwrapping the validator from in a
SmartValidator before checking if it is for bean validation.

Closes gh-31711
2023-12-18 15:25:18 +00:00
rstoyanchev 0a94dce41d Improve HandlerMethod check when method validation applies
Method validation needs to be used for a container such as a List or
Map, but until now we were only checking for a List container.
Moreover, in gh-31530 we improved method validation to also cover
any Collection.

This change aligns with HandlerMethod check for when method validation
applies with the underlying ability of method validation.
2023-12-18 15:25:18 +00:00
Stéphane Nicoll 9b3afcdac7 Merge pull request #31845 from bohub12
* pr/31845:
  Polish "Replace deprecated usage of project.buildDir"
  Replace deprecated usage of project.buildDir

Closes gh-31845
2023-12-18 16:24:11 +01:00
Stéphane Nicoll 8eb524dc4d Polish "Replace deprecated usage of project.buildDir"
See gh-31845
2023-12-18 16:24:02 +01:00
bohub12 dee8108bbc Replace deprecated usage of project.buildDir
See gh-31845
2023-12-18 16:24:02 +01:00
Juergen Hoeller 045c5dc1b4 Detect Jetty 12 "max length exceeded" message in handleParseFailure
Closes gh-31850
2023-12-18 16:18:27 +01:00
Arjen Poutsma 24f8eac12a Improve ByteBuffer copy method
This commit improves JettyWebSocketHandlerAdapter::copyByteBuffer so
that it allocates a buffer large enough for the remaining bytes
contained in the source, instead of allocating one with the capacity of
the source.

Closes gh-31857
2023-12-18 15:23:27 +01:00
Stéphane Nicoll eaf7a28250 Write runtime hints with deterministic order
This commit updates the JSON writers to use a deterministic order for
arrays. Previously, the order could change with the same content,
breaking caching.

Closes gh-31852
2023-12-18 14:57:13 +01:00
Stéphane Nicoll 7965c1969f Merge pull request #31802 from Drezir
* pr/31802:
  Polish "Use String.repeat instead of explicit cycle"
  Use String.repeat instead of explicit cycle

Closes gh-31802
2023-12-18 14:11:35 +01:00
Stéphane Nicoll d0574197ea Polish "Use String.repeat instead of explicit cycle"
See gh-31802
2023-12-18 14:10:16 +01:00
Adam Ostrožlík 63b2787da6 Use String.repeat instead of explicit cycle
See gh-31802
2023-12-18 13:54:03 +01:00
Arjen Poutsma 1ff683b259 Correctly set capacity of remainder in DefaultDataBuffer::split
This commit ensures that the capacity of the remainder buffer after a
split operation is set directly on the field. Calling capacity(int)
caused a new buffer to be allocated.

Closes gh-31848
2023-12-18 11:45:02 +01:00
Stéphane Nicoll 22bf4df290 Polish 2023-12-16 19:19:33 +01:00
Yaklede b56fc50c27 Update copyright headers in spring-test
Closes gh-31853
2023-12-16 14:23:37 +01:00
Sébastien Deleuze d2aa6a98f2 Polishing
Closes gh-31846
2023-12-15 10:12:15 +01:00
T45K bf0819390f Support Kotlin value classes as suspending function arguments
Similar to gh-31698 but for Coroutines.

See gh-31846
2023-12-15 10:11:59 +01:00
dogglezz 503ccb577c Remove unused imports
Closes gh-31851
2023-12-15 09:35:17 +01:00
Stéphane Nicoll 2f7e650122 Merge pull request #31847 from achhibi
* pr/31847:
  Upgrade copyright year of changed file
  Combine conditions for better readability and simplicity

Closes gh-31847
2023-12-15 07:37:26 +01:00
Stéphane Nicoll 68931a2091 Upgrade copyright year of changed file
See gh-31847
2023-12-15 07:36:50 +01:00
achhibi 7f79ccbec0 Combine conditions for better readability and simplicity 2023-12-14 20:29:09 +01:00
Sébastien Deleuze 43c2e51d6e Document BytecodeProviderImpl substitution related issue
See gh-29549
See gh-31051
2023-12-14 15:37:43 +01:00
Spring Builds 66b8f369dc Next development version (v6.1.3-SNAPSHOT) 2023-12-14 10:42:10 +00:00
Juergen Hoeller d4406507d0 Polishing 2023-12-14 00:12:22 +01:00
Juergen Hoeller a612518f96 Check startup/shutdown thread state for close bypass in shutdown hook
See gh-31811
2023-12-14 00:12:12 +01:00
rstoyanchev ec0ec7a0d6 Avoid nested constructor binding if there are no request parameters
Closes gh-31821
2023-12-13 18:06:16 +00:00
Brian Clozel 0970b1dc7a Optimize ContentCachingRequestWrapper allocation
This commit builds on top of changes made in gh-29775 and gh-31737.
Before this change, we would allocate several byte arrays even in cases
of known request size. This could decrease performance when getting the
cached content as it requires merging several arrays and data is not
colocated in memory.

This change ensures that we create a `FastByteArrayOutputStream`
instance with the known request size so that the first allocated segment
can contain the entire content.
If the request size is not know, we will default back on the default
allocation size for the `FastByteArrayOutputStream`.

Closes gh-31834
2023-12-13 18:47:32 +01:00
Sébastien Deleuze a01c6d57bb Inherit parent context in coRouter DSL
This commit also allows context override, as it
is useful for the nested router use case.

Closes gh-31831
2023-12-13 16:00:22 +01:00
Sam Brannen 8d4deca2a6 Introduce test for XML replaced-method element without explicit arg-type
This commit introduces an integration test for the regression fixed in
the previous commit (cd64e6676c).

Closes gh-31826
2023-12-13 15:04:15 +01:00
Juergen Hoeller cd64e6676c Prepare method overrides when bean class gets resolved
See gh-31826
2023-12-13 14:33:13 +01:00
rstoyanchev 2acc7c609f Refine RequestMappingInfo path initialization
Refining the change from 43700302c6 so that
we consistently pick a PathPatternParser (a) if it is provided, and (b)
if both PathPatternParser and PathMatcher are not provided. Also applying
the same in the mutate builder.

See gh-31662
2023-12-13 12:10:53 +00:00
Stéphane Nicoll 409cecfff9 Add custom code generation for bean definition property values
This commits allows ValueCodeGenerator$Delegate implementations to be
loaded from `META-INF/spring/aot.factories` and considered for code
generation of bean definition property values. This default behavior
in DefaultBeanRegistrationCodeFragments can be customized as usual.

Closes gh-31427
2023-12-13 07:14:55 +01:00
Stéphane Nicoll 3c2c9ca186 Extract value code generation to make it reusable
This commit introduces ValueCodeGenerator and its Delegate interface
as a way to generate the code for a particular value. Implementations
in spring-core provides support for common value types such a String,
primitives, Collections, etc.

Additional implementations are provided for code generation of bean
definition property values.

Closes gh-28999
2023-12-13 07:05:58 +01:00
Sam Brannen 75da9c3c47 Scan annotations on method in interface hierarchy only once
Prior to this commit, the AnnotationsScanner used in the
MergedAnnotations infrastructure found duplicate annotations on methods
within multi-level interface hierarchies.

This commit addresses this issue by scanning methods at a given level
in the interface hierarchy using ReflectionUtils#getDeclaredMethods
instead of Class#getMethods, since the latter includes public methods
declared in super-interfaces which will anyway be scanned when
processing super-interfaces recursively.

Closes gh-31803
2023-12-12 18:28:53 +01:00
Sam Brannen 952223dcf9 Polish MergedAnnotation tests 2023-12-12 17:42:58 +01:00
rstoyanchev 125e2902be Polishing contribution
Closes gh-31778
2023-12-12 16:01:23 +00:00
HeartPattern 4d838c1092 Exclude Part from nested constructor binding in WebFlux
See gh-31778
2023-12-12 16:01:23 +00:00
Stéphane Nicoll c75c0ae2d5 Make sure interface method has hints for init/destroy invocation
This commit matches the behavior of the core container when it
invokes a custom init or destroy method. If the custom method is an
interface implementation, the core container attempts to invoke the
method that's defined on the interface. This commit makes sure to also
register a hint for the interface method.

Closes gh-31819
2023-12-12 14:57:35 +01:00
Sam Brannen c0683cd30b Update copyright headers 2023-12-12 14:51:03 +01:00
Sam Brannen 7471fd1dd0 Remove obsolete code 2023-12-12 14:51:03 +01:00
Sam Brannen 1c58511cb2 Polishing 2023-12-12 14:51:03 +01:00
Brian Clozel 8de0fadd09 Upgrade CI to JDK 22 early access 27 2023-12-12 14:47:50 +01:00
Brian Clozel da01e0c6e2 Upgrade CI to Ubuntu Jammy 20231128 2023-12-12 14:47:24 +01:00
Brian Clozel b87852612b Improve "active" metrics handling in WebClient observations
Prior to this commit, the WebClient observations would have a specific
lifecycle where the observation context is build with a
`ClientRequest.Builder` as tracing needs to add an outgoing request
header before the request is made immutable.

With this setup, the metrics observation handler processes the start
event by increasing the "http.client.requests.active" counter and
collecting tags at this point. Because then the immutable request is not
yet fully built or set on the context, the keyvalues collected by the
observation convention at that point can be incomplete.

This commit ensures that a request is always made available in the
context, even if it is updated right after the observation start. The
only difference between the two should be additional tracing headers and
a request attribute holding the current observation context.

Closes gh-31702
2023-12-12 14:41:41 +01:00
Juergen Hoeller 7adc2f0779 Upgrade to Tomcat 10.1.16 and Jetty 12.0.4 2023-12-12 14:26:56 +01:00
Stéphane Nicoll 33b28fe5bf Upgrade to Reactor 2023.0.1
Closes gh-31814
2023-12-12 13:58:24 +01:00
Stéphane Nicoll b85fcb6aec Polish 2023-12-12 13:56:56 +01:00
Arjen Poutsma 134bb6e31f Document exception wrapping in RestClient status handlers
This commit documents the fact that any (Unchecked)IOExceptions or
HttpMessageNotReadableExceptions thrown from the error handler will be
wrapped in a RestClientException.

Closes gh-31783
2023-12-12 13:34:16 +01:00
Juergen Hoeller 240a75f313 Polishing 2023-12-12 12:40:04 +01:00
Juergen Hoeller 6dcba4de2c Avoid double proxying for @Resource @Lazy fallback autowiring
Includes refactored @Resource resolver for AOT with lazy resolution support.

Closes gh-31447
See gh-29614
2023-12-12 12:39:59 +01:00
Juergen Hoeller 6bb9775309 Declare isStatic and releaseTarget as default methods on TargetSource
Closes gh-31820
2023-12-12 12:39:52 +01:00
Juergen Hoeller eae53560e4 Use ReentrantLock to skip intermediate close attempt from shutdown hook
See gh-31811
2023-12-12 12:39:45 +01:00
Brian Clozel f0abdf2264 Upgrade to Mockito 5.8.0
See gh-31459
2023-12-12 11:22:41 +01:00
Brian Clozel c7f24efc27 Upgrade to Groovy 4.0.16
See gh-31459
2023-12-12 11:22:07 +01:00
Brian Clozel 07d2571e0b Avoid race conditions while restructuring ConcurrentReferenceHashMap
Prior to this commit, the `ConcurrentReferenceHashMap#restructure`
operation would null out the entire references array before starting the
restructuring operation (in case resizing is not necessary).

This could cause at runtime race conditions where a lookup operation
would return null, when the value is actually cached but not accesible
during the restructuring phase.

This commit ensures that, when resizing is not required, a new reference
list is built (purged of null entries) and then assigned to the
reference array. This way, concurrent reads will not return null for
existing entries and there are less chances of re-calculating cache
entries during the restructuring phase.

Closes gh-31008
2023-12-12 10:18:58 +01:00
Juergen Hoeller 8c51315cd6 Avoid potential refresh deadlock with registerShutdownHook
Closes gh-31811
2023-12-11 21:35:58 +01:00
Sébastien Deleuze e8cd26bbf0 Update the badge to 6.1.x in README.md 2023-12-11 21:32:36 +01:00
Sébastien Deleuze 9aded3fcad Fix a NPE in proxied suspending functions
Closes gh-31809
2023-12-11 21:21:34 +01:00
Sébastien Deleuze aabe4d0b07 Pickup CoroutineContext saved by CoWebFilter in coRouter
Closes gh-31793
2023-12-11 19:03:35 +01:00
rstoyanchev 570074259d Minor updates in HandlerMappingIntrospector
Required by Spring Security to complete work on
https://github.com/spring-projects/spring-security/issues/14128

The setCache and resetCache methods used from createCacheFilter are now
public. Generally they don't need to be used outside of the Filter if
only making checks against the current request. Spring Security, however,
makes additional checks against requests with alternative paths.
2023-12-11 15:38:34 +00:00
Stéphane Nicoll f962211e0a Start building against Reactor 2023.0.1 snapshots
See gh-31814
2023-12-11 15:00:19 +01:00
Stéphane Nicoll 6077c998d1 Upgrade to Micrometer 1.12.1
Closes gh-31813
2023-12-11 14:55:55 +01:00
Arjen Poutsma 57b8100a06 Copy headers map in RestClientResponseException to ensure serializability
This commit ensures that the HttpHeaders used are serializable by making
 a copy.

Closes gh-31787
2023-12-11 14:02:31 +01:00
Sam Brannen 7432a96b48 Polish contribution
See gh-31808
2023-12-11 13:42:03 +01:00
Mathieu AMBLARD (u118971) a01384068a Fix Comparators.nullsLow and Comporators.nullsHigh behavior
Commit 33454a4007 introduced a regression in Comparators.nullsLow() and
Comporators.nullsHigh().

This commit updates the code so that nullsLow() sorts null values lower
than non-null values and nullsHigh sorts null values higher than
non-null values.

See gh-25478
Closes gh-31808
2023-12-11 13:18:24 +01:00
Sébastien Deleuze d75a7c3818 Support multiple CoWebFilter changing the context
This commit ensures CoWebFilter merges the exchange
CoroutineContext with the filter one if needed.

Closes gh-31792
2023-12-11 11:35:19 +01:00
Stéphane Nicoll e2c2268c39 Add AOT support for @Resource
This commit adds ahead of time support for @Resource on fields and
methods. Lookup elements are discovered and code is generated to replace
that introspection at runtime.

Closes gh-29614
2023-12-11 11:04:13 +01:00
Juergen Hoeller b510bc3bab Reuse generated key for get+put within same cacheable operation
Closes gh-31789
2023-12-10 20:14:49 +01:00
Sam Brannen b6364e3665 Polish Javadoc 2023-12-10 18:25:01 +01:00
Juergen Hoeller f29bfd9769 Polishing 2023-12-10 00:28:51 +01:00
Juergen Hoeller 361dfd1ae4 Polishing 2023-12-09 23:51:18 +01:00
Juergen Hoeller 8704ad98a7 Clear caches which are not needed after singleton instantiation
Closes gh-28293
2023-12-09 23:50:54 +01:00
Juergen Hoeller c57b7e8418 Introduce ClassFormatException and spring.classformat.ignore property
Closes gh-27691
2023-12-09 20:03:57 +01:00
Juergen Hoeller 77b0382a6c Bypass getParameterType by default for PostgreSQL and SQL Server drivers
Closes gh-25679
2023-12-09 20:03:51 +01:00
Stéphane Nicoll a7f9da1670 Merge pull request #31801 from JuHyun419
* pr/31801:
  Remove unused code

Closes gh-31801
2023-12-09 16:42:17 +01:00
juhyun b782747472 Remove unused code
See gh-31801
2023-12-09 16:40:23 +01:00
Juergen Hoeller 69bc4e2828 Delegation support for JDBC 4.3 ConnectionBuilder and ShardingKeyBuilder
Also moves ShardingKeyProvider to datasource package and declares getSuperShardingKey as default method.

Closes gh-31795
See gh-31506
2023-12-08 23:52:22 +01:00
Mohammed Bekraoui e4e2224449 Support direct shard database operation routing in Spring JDBC (#31506)
Introduce ShardingKeyDataSourceAdapter to get shard connections.

This commit introduces a DataSource proxy, that changes the behavior of the getConnection method to use the `createConnectionBuilder()` api to acquire direct shard connections. The shard connection is acquired by specifying a `ShardingKey` that is correspondent to the wanted shard.
2023-12-08 23:09:39 +01:00
Gabriel Ramirez d919930d83 Fix link text in WebFlux @⁠HttpExchange section of reference docs
Closes gh-31796
2023-12-08 18:31:17 +01:00
Juergen Hoeller afc1f37616 Support for SQL Server named parameter binding (aligned with Sybase)
Closes gh-26072
See gh-30231
2023-12-08 16:38:43 +01:00
Giuseppe Milicia 748dd94dab Fix Sybase SimpleJdbcCall named parameter binding 2023-12-08 16:15:51 +01:00
Henning Poettker b3a3b79b44 Adds MySQLIdentityColumnMaxValueIncrementer
The new `DataFieldMaxValueIncrementer` can be used with identity columns in MySQL 8.0 or later.
2023-12-08 16:12:29 +01:00
Sébastien Deleuze 91b9a75371 Box Kotlin value class parameters in web endpoint
In order to avoid "java.lang.IllegalArgumentException:
object is not an instance of declaring class" errors.

Closes gh-31698
2023-12-08 15:27:08 +01:00
Stéphane Nicoll b78aed99ea Provide a dedicated exception if ScheduledExecutor is not configured
While it is not easily possible to create a ConcurrentTaskScheduler
with no scheduled executor, DefaultManagedTaskScheduler has a default
constructor that does that as the JNDI lookup happens in the regular
afterPropertiesSet callback. If such an instance is created manually,
it can throw an unhelpful NullPointerException if one attempts to
schedule a task.

This commit updates ConcurrentTaskScheduler to flag that the scheduled
executor could be `null` and check if that's the case before using it.
This now throws a dedicated exception that should hopefully provide
better context for those upgrading.

See gh-27914

Closes gh-31751
2023-12-08 15:06:55 +01:00
Stéphane Nicoll 2eba3510f7 Annotate generated classes with @Generated
This commit annotates every generated class with `@Generated` so that
build tools can recognize and ignore those types if necessary.

Closes gh-30824
2023-12-08 14:24:53 +01:00
Stéphane Nicoll 56afd38148 Delete .mailmap
This file is incomplete and has outdated content. Given that several
core committers are not even listed, it does not seem to serve a
valid purpose anymore.

Closes gh-31740
2023-12-08 14:15:32 +01:00
Stéphane Nicoll 33e4129155 Do not discover annotation processors from the classpath in tests
Previously, if an annotation processors was present in the classpath
it was executed as part of tests using `TestCompiler`.

This commit updates `TestCompiler` to always set the annotation
processors to use. By default, this sets an empty list which does not
use annotation processing.

Closes gh-31791
2023-12-08 14:11:38 +01:00
Stéphane Nicoll 0717ea5ca5 Polish 2023-12-08 12:17:44 +01:00
Juergen Hoeller 3b4c7a8906 Revise LazyConnectionDataSourceProxy for late connection properties check
Includes special support for a read-only DataSource in addition to the regular target DataSource, avoiding the overhead of switching the Connection's read-only flag at the beginning and end of every transaction.

Closes gh-29931
Closes gh-31785
Closes gh-19688
Closes gh-21415
2023-12-07 23:14:17 +01:00
Rossen Stoyanchev 2e07f9ab33 DefaultWebClient exposes full URI template as request attribute
Closes gh-30027
2023-12-07 12:16:22 +00:00
rstoyanchev dd23b1d156 Add mappedHandler Predicate to AbstractHandlerExceptionResolver
Closes gh-26772
2023-12-07 12:16:22 +00:00
rstoyanchev 753409083d Add urlDecode property to ServletCookieValueMethodArgumentResolver
Closes gh-26989
2023-12-07 12:16:22 +00:00
Stéphane Nicoll e36d035f58 Remove leftovers
See gh-31690
2023-12-07 10:59:01 +01:00
Sam Brannen 302cdeeee6 Clean up warnings in JdbcTransactionManagerTests 2023-12-06 21:35:02 +01:00
Brian Clozel 61dd9fce73 Revert ValidationMode.CALLBACK on JPA bootstrap
In gh-30549 we applied changes to the `DefaultPersistenceUnitManager` to
use the `ValidationMode.CALLBACK` to better detect invalid validation
setup and enforce bootstrap failures in those cases.

Unfortunately, doing so disables the detection of validation annotation
on entities during the schema creation phase. This is a known Hibernate
issue. This commit reverts this change until HHH-12287 is fixed.

Fixes gh-31726
2023-12-06 18:34:42 +01:00
Sam Brannen 7a221eb581 Update Javadoc for @⁠ComponentScan regarding local overrides
See gh-31704
2023-12-06 18:00:37 +01:00
Sam Brannen 2e5d1daeff Polishing 2023-12-06 17:59:40 +01:00
Sam Brannen bf6cb7cd89 Delete manually crafted section summary for Java-based Container Config
Closes gh-31777
2023-12-06 17:40:12 +01:00
Sam Brannen 2c053b34f0 Delete manually crafted section summary for the SpEL Language Reference
Closes gh-31776
2023-12-06 17:27:35 +01:00
Sam Brannen 438c3818cc Replace System.getProperties().remove(x) with System.clearProperty(x)
This commit migrates to the not-so-new System.clearProperty() method
introduced in Java 1.5.
2023-12-06 17:11:46 +01:00
Sam Brannen f14b122c9c Fix #this and #root variable examples in SpEL documentation
This commit actually introduces a new example for #root variable usage,
which was previously missing.

Closes gh-31770
2023-12-06 16:54:03 +01:00
Sam Brannen 9f305bfaab Polish SpEL examples and tests 2023-12-06 16:54:03 +01:00
Sébastien Deleuze d410872e4f Polish CookieIntegrationTests 2023-12-06 15:01:09 +01:00
Sébastien Deleuze 8fe2c780df Support cookies with the same name with Reactor Netty
Ignore the related test with Undertow due to a bug in
their cookies handling.

Closes gh-28490
2023-12-06 15:01:09 +01:00
Stéphane Nicoll b53ffa3855 Merge pull request #31700 from quaff
* pr/31700:
  Polish contribution
  Add support for location patterns in ResourceArrayPropertyEditor

Closes gh-31700
2023-12-06 15:00:30 +01:00
Stéphane Nicoll 25537938d6 Polish contribution
See gh-31700
2023-12-06 15:00:14 +01:00
Yanming Zhou 9704b809b1 Add support for location patterns in ResourceArrayPropertyEditor
This commit adds support for comma delimited location patterns in
ResourceArrayPropertyEditor.

See gh-31700
2023-12-06 15:00:14 +01:00
Arjen Poutsma 0e6c17f518 Process tokens after each feed in Jackson2Tokenizer
This commit ensures that we process after each fed buffer in
Jackson2Tokenizer, instead of after all fed buffers.

Closes gh-31747
2023-12-06 14:31:05 +01:00
Sam Brannen 1afea0b144 Fix and polish Javadoc for MimeTypeUtils 2023-12-06 14:30:16 +01:00
Johnny Lim 7b95bd72f7 Fix condition for "Too many elements" in MimeTypeUtils.sortBySpecificity()
See gh-31254
Closes gh-31769
2023-12-06 14:09:53 +01:00
Sam Brannen fdcea58a53 Polishing 2023-12-06 12:36:04 +01:00
Arjen Poutsma ef4ffa0005 Support empty part in DefaultPartHttpMessageReader
This commit fixes a bug in DefaultPartHttpMessageReader's
MultipartParser, due to which the last token in a part window was not
properly indicated.

Closes gh-30953
2023-12-06 12:21:37 +01:00
Sébastien Deleuze 2e3d13331a Document @ModelAttribute usage with native images
Closes gh-31765
2023-12-06 12:13:33 +01:00
Sam Brannen 448e753184 Honor classValuesAsString in getMergedRepeatableAnnotationAttributes()
Closes gh-31768
2023-12-06 12:09:39 +01:00
Sam Brannen 6b53f37030 Favor local @⁠ComponentScan annotations over meta-annotations
Work performed in conjunction with gh-30941 resulted in a regression.
Specifically, prior to Spring Framework 6.1 a locally declared
@⁠ComponentScan annotation took precedence over @⁠ComponentScan
meta-annotations, which allowed "local" configuration to override
"meta-present" configuration.

This commit modifies the @⁠ComponentScan search algorithm so that
locally declared @⁠ComponentScan annotations are once again favored
over @⁠ComponentScan meta-annotations (and, indirectly, composed
annotations).

See gh-30941 Closes gh-31704
2023-12-06 11:40:25 +01:00
Yanming Zhou afcd03bddc Replace assertThat(x.isEmpty()).isTrue() with assertThat(x).isEmpty()
Search for   : assertThat\((.+).isEmpty\(\)\).isTrue\(\)
Replace with : assertThat($1).isEmpty()

Search for   : assertThat\((.+).isEmpty\(\)\).isFalse\(\)
Replace with : assertThat($1).isNotEmpty()

Closes gh-31758
2023-12-06 10:04:56 +01:00
Yanming Zhou 7b16ef90f1 Replace assertThat(x.equals(y)) with assertThat(x).isEqualTo(y)
Search for   : assertThat\((.+)\.equals\((\w+)\)\)\.isTrue\(\)
Replace with : assertThat($1).isEqualTo($2)

Search for   : assertThat\((.+)\.equals\((\w+)\)\)\.isFalse\(\)
Replace with : assertThat($1).isNotEqualTo($2)

Closes gh-31763
2023-12-06 09:50:15 +01:00
Yanming Zhou e2852e7355 Replace assertThat(x.contains(y)).isTrue() with assertThat(x).contains(y)
Search for   : assertThat\((.+)\.contains\((.+)\)\)\.isTrue\(\)
Replace with : assertThat($1).contains($2)

Search for   : assertThat\((.+)\.contains\((.+)\)\)\.isFalse\(\)
Replace with : assertThat($1).doesNotContain($2)

Closes gh-31762
2023-12-06 09:48:49 +01:00
Yanming Zhou 1a63257b12 Add missing @Test
Closes gh-31761
2023-12-06 09:48:08 +01:00
Yanming Zhou 66e405525b Replace assertThat(x instanceof y).isTrue() with assertThat(x).isInstanceOf(y.class)
Search for   : assertThat\((.+) instanceof (\w+)\)\.isTrue\(\)
Replace with : assertThat($1).isInstanceOf($2.class)

Search for   : assertThat\((.+) instanceof (\w+)\)\.isFalse\(\)
Replace with : assertThat($1).isNotInstanceOf($2.class)

Closes gh-31760
2023-12-06 09:46:44 +01:00
Yanming Zhou 59815cefce Replace assertThat(x.get(i)). with assertThat(x).element(i).
Search for   : assertThat\((.+)\.get\((\d+)\)\)\.
Replace with : assertThat($1).element($2).

Closes gh-31759
2023-12-06 09:43:59 +01:00
Yanming Zhou 785ad399e9 Replace assertThat(x.iterator().next()) with assertThat(x).element(0)
Search for   : assertThat\((.+).iterator\(\).next\(\)\)
Replace with : assertThat($1).element(0)
2023-12-06 10:52:39 +08:00
Sébastien Deleuze 3f9a809c32 Improve @RegisterReflectionForBinding for enums
Closes gh-31570
2023-12-05 16:53:51 +01:00
Sam Brannen c74d60b9fe Polishing 2023-12-05 16:14:13 +01:00
Sam Brannen db48813181 Polish contribution
See gh-31757
2023-12-05 16:14:13 +01:00
HyeongMokJeong a596c0e226 Introduce overloaded MockPart constructor that accepts the Content-Type
Closes gh-31757
2023-12-05 15:55:33 +01:00
Sam Brannen 462ef95904 Fix typo in Javadoc 2023-12-05 13:05:54 +01:00
Arjen Poutsma 52d4b83dba Partially revert RequestPredicates attribute handling
This commit partially reverts 39786e4790
and c5c843696b, as the approach taken did
not take into account request predicates that query request attributes,
including path variables.

Closes gh-31732
2023-12-05 12:30:15 +01:00
Sam Brannen aa347e5fe6 Polish MutablePropertyValuesTests 2023-12-05 11:43:57 +01:00
Sam Brannen ceba4162bb Replace assertThat(!x).isTrue() with assertThat(x).isFalse()
Search for   : assertThat\(!(.+)\).isTrue\(\)

Replace with : assertThat(\1).isFalse()
2023-12-05 11:41:57 +01:00
Stéphane Nicoll 21560bccd3 Merge pull request #31752 from quaff
* pr/31752:
  Polish "Use idiomatic AssertJ map assertions"
  Use idiomatic AssertJ map assertions

Closes gh-31752
2023-12-05 10:41:09 +01:00
Stéphane Nicoll 1da40b84e7 Polish "Use idiomatic AssertJ map assertions"
See gh-31752
2023-12-05 10:39:33 +01:00
Yanming Zhou 6f11716b6f Use idiomatic AssertJ map assertions
See gh-31752
2023-12-05 10:01:38 +01:00
Juergen Hoeller 47fe61ef79 Introduce lazyTransactionalConnections flag on TransactionAwareDataSourceProxy
Includes revision of JDBC transaction tests.

Closes gh-29423
2023-12-04 18:24:30 +01:00
Juergen Hoeller 8a82da43c9 Defensively wrap fixed-delay task on scheduler thread
Closes gh-31749
2023-12-04 18:20:44 +01:00
Sam Brannen cb60f74556 Stop referring to JDO PersistenceManager in comments 2023-12-04 16:50:53 +01:00
Sam Brannen 62b3d7a963 Update copyright headers 2023-12-04 16:47:25 +01:00
Sam Brannen b69e5acfe3 Revert use of yield in switch expressions due to Eclipse compiler error
See gh-31531
2023-12-04 16:47:25 +01:00
Sam Brannen d71853f105 Polish contribution
See gh-31531
2023-12-04 16:47:25 +01:00
Yanming Zhou 490b5c77fc Use switch expression where feasible 2023-12-04 15:42:55 +01:00
Sam Brannen 8ed04b5dd1 Polish contribution
See gh-31723
2023-12-04 15:17:52 +01:00
Per Lundberg 87d37a21aa Link to spring.factories used in the TestContext framework in the ref docs
Closes gh-31723
2023-12-04 15:04:12 +01:00
Sam Brannen eee2569bff Polishing 2023-12-04 15:04:12 +01:00
Stéphane Nicoll dbec3f1fa1 Polish 2023-12-04 14:27:29 +01:00
Sam Brannen e870912fa2 Polish Javadoc for MockRestServiceServer
See gh-31741
2023-12-03 19:24:46 +01:00
Donghun Shin 99f50ebeb4 Fix Javadoc for MockRestServiceServer.bindTo(RestClient.Builder)
Closes gh-31741
2023-12-03 19:15:35 +01:00
Sam Brannen cd62dfe3a9 Polish FastByteArrayOutputStream[Tests]
See gh-31737
2023-12-02 16:31:28 +01:00
Patrick Strawderman 7cdacf3083 Introduce toString(Charset) in FastByteArrayOutputStream
This commit introduces a toString() overload in
FastByteArrayOutputStream that accepts a Charset in order to mirror the
method that was introduced in ByteArrayOutputStream in JDK 10,
including a special case for when a single buffer is in use internally
to avoid the need to resize.

This commit also updates getContentAsString() in
ContentCachingRequestWrapper to use this new toString(Charset) method.

Closes gh-31737
2023-12-02 16:31:28 +01:00
Stéphane Nicoll 0bec8125a4 Merge pull request #31736 from tylerbertrand
* pr/31736:
  Use relative path for javadoc overview

Closes gh-31736
2023-12-02 16:22:19 +01:00
Tyler Bertrand da32e3d39e Use relative path for javadoc overview
See gh-31736
2023-12-02 16:19:17 +01:00
Sam Brannen 47cdc7c5f0 Update copyright headers
See gh-31738
2023-12-02 15:32:46 +01:00
dogglezz decb22a93d Polish Javadoc
Closes gh-31738
2023-12-02 15:31:39 +01:00
rstoyanchev d59b2924d3 Exclude any Java library type from nested constructor binding
Closes gh-31709
2023-12-01 17:04:49 +00:00
Sam Brannen c05b4ce776 Suppress warnings in Gradle build 2023-12-01 15:44:37 +01:00
Sam Brannen 3a53446a2b Upgrade to Gradle 8.5
Closes gh-31734
2023-12-01 15:37:55 +01:00
Arjen Poutsma d204dd2dbe Use IntrospectingClientHttpResponse in RestClient
This commit ensures that the RestClient uses the
IntrospectingClientHttpResponse to verify whether the response has a
body, and return null if it does not.

See gh-12671
Closes gh-31719
2023-12-01 14:22:58 +01:00
Stéphane Nicoll 0dbb0f5c14 Merge pull request #31731 from kilink
* pr/31731:
  Avoid byte array copy in getContentAsString

Closes gh-31731
2023-12-01 10:58:44 +01:00
Patrick Strawderman e452c2e89c Avoid byte array copy in getContentAsString
The getContentAsString method was originally added in d9b8826 to avoid
the extra copying inherent to calling ByteArrayOutputStream.toByteArray;
however, in f83c609 the class was updated to instead use
FastByteArrayOutputStream, and in the process the extra copy was brought
back when getContentAsString was changed to call toByteArray.

Switch to calling toByteArrayUnsafe, a method provided by
FastByteArrayOutputStream, which avoids the extra copy; since we
immediately pass the byte array to the String constructor, and it isn't
accessed anywhere else, the usage is safe.

See gh-31731
2023-12-01 10:47:38 +01:00
Sam Brannen 6ea9fdbf77 Polishing 2023-11-30 19:04:59 +01:00
Sébastien Deleuze 8ff687b68c Polish BeanDefinitionDsl.kt 2023-11-30 18:17:47 +01:00
Sébastien Deleuze bf1c179b7f Allow to set the order from Kotlin bean DSL
Closes gh-30849
2023-11-30 18:09:00 +01:00
Sébastien Deleuze 16ac495084 Introduce ORDER_ATTRIBUTE on AbstractBeanDefinition
This commit allows to define a bean order programmatically
at bean definition level (functional equivalent of
`@Order`).

If specified, the order attribute defined at bean
definition level overrides potential values set with
`@Order`.

See gh-30849
2023-11-30 18:09:00 +01:00
Sam Brannen a506238ef6 Polishing 2023-11-30 17:59:58 +01:00
Sam Brannen 33af98b6d6 Document need for -parameters flag in cache key generation exception messages
Closes gh-31675
2023-11-30 17:51:54 +01:00
Juergen Hoeller edfe179291 Polishing 2023-11-30 16:36:45 +01:00
Juergen Hoeller 5f9702b2a4 Introduce rollbackBeforeClose property and AutoCloseable implementation
Closes gh-27249
2023-11-30 16:36:32 +01:00
Juergen Hoeller c56c304536 PathEditor considers single-letter URI scheme as NIO path candidate
Closes gh-29881
2023-11-30 14:16:05 +01:00
rstoyanchev 8090a52f5c ForwardedHeaderFilter supports ERROR requestUri attribute
Closes gh-30828
2023-11-30 13:10:17 +00:00
rstoyanchev 19bca03aa2 Polishing in ForwardedHeaderFilter
See gh-30828
2023-11-30 13:10:17 +00:00
rstoyanchev 0e6e225fb9 Implement messageSize methods in JettyWebSocketSession
Closes gh-28325
2023-11-30 13:10:17 +00:00
rstoyanchev 8ca82120e0 Add missing exception name to DisconnectedClientHelper
Closes gh-31717
2023-11-30 13:10:17 +00:00
rstoyanchev 9ade52dbe2 Exclude Part and MultipartFile from nested constructor binding
Closes gh-31669
2023-11-30 13:10:17 +00:00
Yanming Zhou feef98b73c Correct conversion from Resource[] with length 1 to Collection<Resource>
Fix GH-31693
2023-11-30 14:05:13 +01:00
Juergen Hoeller 4a6c3e8f5d Fix reactive retrieval of cached null value for empty Mono
Closes gh-31722
2023-11-30 12:05:16 +01:00
Sébastien Deleuze f77713b7e0 Document testing automatic checkpoint/restore at startup
Closes gh-31724
2023-11-30 11:35:01 +01:00
Stéphane Nicoll dc5bef16b4 Polish Default Profile section
Closes gh-30319
2023-11-29 17:47:27 +01:00
Juergen Hoeller f3b1f37000 Process URL path for filename extraction if URI does not expose path
Closes gh-31718
2023-11-29 17:08:59 +01:00
Sébastien Deleuze df00aafdff Add a nested generics test for GenericTypeResolver
Closes gh-31690
2023-11-29 15:12:07 +01:00
Sébastien Deleuze 7cf124b696 Revert "Support WildcardType resolution in GenericTypeResolver"
This reverts commit f075120675.

See gh-22313
See gh-31690
2023-11-29 15:09:57 +01:00
Brian Clozel 35fcbae8c6 Fix reactive HTTP server Observation instrumentation
Prior to this commit, regressions were introduced with gh-31417:

1. the observation keyvalues would be inconsistent with the HTTP response
2. the observation scope would not cover all controller handlers, causing
  traceIds to be missing

The first issue is caused by the fact that in case of error signals, the
observation was stopped before the response was fully committed, which
means further processing could happen and update the response status.
This commit delays the stop event until the response is committed in
case of errors.

The second problem is caused by the change from a `contextWrite`
operator to using the `tap` operator with a `SignalListener`. The
observation was started in the `doOnSubscription` callback, which is too
late in some cases. If the WebFlux controller handler is synchronous
non-blocking, the execution of the handler is performed before the
subscription happens. This means that for those handlers, the
observation was not started, even if the current observation was
present in the reactor context. This commit changes the
`doOnSubscription` to `doFirst` to ensure that the observation is
started at the right time.

Fixes gh-31703
Fixes gh-31706
2023-11-29 14:39:56 +01:00
Stéphane Nicoll c8e6315a67 Polish 2023-11-29 10:08:20 +01:00
Stéphane Nicoll 61be452402 Quote name attribute if necessary
This commit updates MetadataNamingStrategy to quote an ObjectName
attribute value if necessary. For now, only the name attribute is
handled as it is usually a bean name, and we have no control over
its structure.

Closes gh-23608
2023-11-28 17:05:06 +01:00
Sam Brannen 0cbbd3a0d5 Polishing 2023-11-28 16:21:58 +01:00
Stéphane Nicoll c92a0bd493 Prevent AotDetector to be initialized at build-time
This commit moves the condition used by `@DisabledInAotMode` to a
concrete implementation rather than using `@DisabledIf` as it causes
build initialization in a native image.

Closes gh-31705
2023-11-28 15:46:31 +01:00
Stéphane Nicoll 755fd75512 Merge pull request #31694 from quaff
* pr/31694:
  Upgrade copyright year of changed file
  Use AssertJ isInstanceOf where feasible

Closes gh-31694
2023-11-28 12:58:14 +01:00
Stéphane Nicoll f8a40555af Upgrade copyright year of changed file
See gh-31694
2023-11-28 12:53:54 +01:00
Yanming Zhou 64d5e904e8 Use AssertJ isInstanceOf where feasible
See gh-31694
2023-11-28 12:49:32 +01:00
Stéphane Nicoll 4e2d357318 Remove list of supported websocket servers
This commit removes a list of hardcoded servers and version as this is
bound to get outdated and the reference guide/wiki is a more suitable
place for this.
2023-11-27 16:31:09 +01:00
Stéphane Nicoll 264ec517f2 Polish 2023-11-27 16:31:09 +01:00
Stéphane Nicoll b2e3be10d4 Add test to reproduce behavior
See gh-24502
2023-11-27 16:31:09 +01:00
Sam Brannen 246833329f Register runtime hints for skipped exceptions in the TestContext framework
Closes gh-31479
2023-11-27 15:42:20 +01:00
rstoyanchev 43700302c6 RequestMappingInfo defaults to PathPatternParser
This changes ensures RequestMappingInfo uses PathPatternParser by default
as all AbstractHandlerMapping implementations do as of 6.0.

RequestMappingInfo instances are typically created internally and aligned with
the RequestMappingHandlerMapping in terms of path mapping options.
If a RequestMappingInfo is registered programmatically, the caller needs to also
ensure they are aligned. However, if the two should be aligned by default.

Closes gh-31662
2023-11-27 10:28:14 +00:00
rstoyanchev 54ecbb2bc8 Update link to stompjs library
Closes gh-28409
2023-11-27 10:28:14 +00:00
Stéphane Nicoll 9eb2f29d4a Move sample to unit test
See gh-28904
2023-11-27 07:58:19 +01:00
Sam Brannen 97264c77dd Consistently log exceptions from TestExecutionListeners at WARN level
Prior to this commit, the TestContextManager logged an exception from a
TestExecutionListener at WARN level except in prepareTestInstance()
where such an exception was logged at ERROR level (except for a skipped
exception which is logged at INFO level).

For consistency, this commit modifies TestContextManager so that it
always logs non-skipped exceptions from TestExecutionListeners at WARN
level.

Closes gh-31688
2023-11-26 12:44:13 +01:00
Sam Brannen b17f3bc07b Polishing 2023-11-26 12:31:15 +01:00
Sam Brannen a15f472898 Include scroll() in SharedEntityManagerCreator's queryTerminatingMethods
This commit supports the scroll() and scroll(ScrollMode) methods from
Hibernate's Query API in SharedEntityManagerCreator's query-terminating
methods set.

Closes gh-31682
2023-11-26 12:12:54 +01:00
Stéphane Nicoll 0785256b2f Match HandlerMapping lookup to bean signature
This commit makes sure to initialize any HandlerMapping defined in the
context when searching for resource handlers. Previously, the detection
algorithm was looking up for `SimpleUrlHandlerMapping` while the
declared target type in WebMvcConfigurationSupport is HandlerMapping.
If the application uses lazy initialization, the lookup algorithm would
not force that bean to be initialized.

Closes gh-25488
2023-11-26 09:59:12 +01:00
Sam Brannen 95e250d4bd Log test aborted exceptions at INFO level in the TestContext framework
Prior to this commit, any time an aborted/skipped exception was thrown
by a TestExecutionListener, the TestContextManager unconditionally
logged the exception at WARN level -- or ERROR level for
prepareTestInstance() callbacks.

Regarding the latter, an aborted/skipped exception is certainly not an
ERROR, and in general the associated log output is very verbose
(including a stack trace) and not something the user should be warned
about it.

To improve the user experience, this commit revises TestContextManager
so that it logs such exceptions at INFO level.

Specifically, the following types of exceptions are considered
aborted/skipped exceptions.

- JUnit Jupiter: org.opentest4j.TestAbortedException
- JUnit 4 org.junit.AssumptionViolatedException
- TestNG: org.testng.SkipException

Closes gh-31479
2023-11-25 18:12:43 +01:00
Sam Brannen dbad9fd208 Update copyright headers 2023-11-25 14:59:40 +01:00
Sam Brannen 657b1c6455 Document need for -parameters flag in exception messages
Closes gh-31675
2023-11-25 14:53:56 +01:00
Sam Brannen 23dc5696d9 Polish contribution
See gh-31679
2023-11-25 14:26:45 +01:00
RedStainedInk a56bf87476 Clarify that DI is a type of IoC
The documentation currently states that Inversion of Control (IoC) and
Dependency Injection (DI) are the same thing. Although the two terms
are related, they are not synonymous: DI is a type of IoC.

I believe this change is important because using the terms
interchangeably really muddies the water about the meaning of these two
fundamental concepts of software frameworks.

Closes gh-31679
2023-11-25 14:15:52 +01:00
Stéphane Nicoll c2745de60c Polish 2023-11-25 09:57:13 +01:00
Juergen Hoeller 710373d286 Consider generics in equals method (for ConversionService caching)
Closes gh-31672
2023-11-24 23:25:59 +01:00
Juergen Hoeller 0599320bd8 Filter candidate methods by name first (for more efficient sorting)
Closes gh-28377
2023-11-24 23:25:28 +01:00
Juergen Hoeller 8921be18de Properly return loaded type even if identified as reloadable
Closes gh-31668
2023-11-24 23:25:01 +01:00
Juergen Hoeller 6ff75f157b Detect current schema as indicated by JDBC Connection
Closes gh-28723
2023-11-24 23:24:20 +01:00
Brian Clozel 15d9d9d06a Add current observation context in ClientRequest
Prior to this commit, `ExchangeFilterFunction` could only get the
current observation from the reactor context. This is particularly
useful when such filters want to add KeyValues to the observation
context.

This commit makes this use case easier by adding the context of the
current observation as a request attribute. This also aligns the
behavior with other instrumentations.

Fixes gh-31609
2023-11-24 17:36:15 +01:00
Krane 894dce7cd8 Optimize loops on BeanDefinitionPropertiesCodeGenerator
Closes gh-31650
2023-11-24 16:30:24 +01:00
Stéphane Nicoll 34031ebea9 Escape schema and function name patterns if necessary
The JDBC API that retrieves a proedure or a function allows to specify
patterns for the schema and the procedure name. So far, we've called
this API with the value as is, which does not work if either contains
a wildcard characters that need to be escaped.

This commit updates GenericCallMetadataProvider to escape, if necessary,
the schema or procedure name using the search string escape from the
database metadata.

Closes gh-22725
2023-11-24 15:49:41 +01:00
Brian Clozel b2757d9a21 Add Javadoc to MockHttpServletResponse#getErrorMessage
Closes gh-31386
2023-11-24 14:41:36 +01:00
Sébastien Deleuze 655b4aacb7 Upgrade to Kotlin 1.9.21
Closes gh-31667
2023-11-24 10:43:40 +01:00
Stéphane Nicoll fb4455b396 Polish 2023-11-24 08:38:47 +01:00
Stéphane Nicoll 677b03c36d Merge pull request #31663 from quaff
* pr/31663:
  Polish "Polish GenericTypeResolver Javadoc"
  Polish GenericTypeResolver Javadoc

Closes gh-31663
2023-11-24 08:32:37 +01:00
Stéphane Nicoll 85aa4b65dc Polish "Polish GenericTypeResolver Javadoc"
See gh-31663
2023-11-24 08:30:40 +01:00
Yanming Zhou 0b61755ea3 Polish GenericTypeResolver Javadoc
See gh-31663
2023-11-24 08:28:27 +01:00
Brian Clozel 3bcd30e811 Remove API diff Gradle plugin configuration
We have not published API diffs for a while now so we should remove the
configuration entirely from our build.
2023-11-23 16:19:20 +01:00
Juergen Hoeller 121e3540cc Clear cached executors in setBeanFactory (for reused AspectJ aspect)
Closes gh-28201
2023-11-23 16:15:01 +01:00
Juergen Hoeller 0d8dee2878 Apply fallback for proxy with negative match or annotation pointcut
See gh-30534
2023-11-23 16:14:33 +01:00
Yanming Zhou 3a6d0c1d5b Always fall back to original method if annotation pointcut used
Prior to this commit, AspectJExpressionPointcut doesn't fall back to original method if `!@annotation()` is used, it can cause false positive result.

Fix GH-27119
2023-11-23 16:01:18 +01:00
Stéphane Nicoll 16c6376b3f Merge pull request #31659 from Johannes-Rost
* pr/31659:
  Polish "Polish RestClient Javadoc"
  Polish RestClient Javadoc

Closes gh-31659
2023-11-23 13:01:37 +01:00
Stéphane Nicoll 487dbf8140 Polish "Polish RestClient Javadoc"
See gh-31659
2023-11-23 12:59:03 +01:00
johannesrost e95f8d2922 Polish RestClient Javadoc
See gh-31659
2023-11-23 12:38:16 +01:00
Spring Builds 52b40ffb03 Next development version (v6.1.2-SNAPSHOT) 2023-11-23 08:58:29 +00:00
2503 changed files with 42839 additions and 29110 deletions
-36
View File
@@ -1,36 +0,0 @@
Juergen Hoeller <jhoeller@vmware.com>
Juergen Hoeller <jhoeller@vmware.com> <jhoeller@pivotal.io>
Juergen Hoeller <jhoeller@vmware.com> <jhoeller@gopivotal.com>
Rossen Stoyanchev <rstoyanchev@vmware.com>
Rossen Stoyanchev <rstoyanchev@vmware.com> <rstoyanchev@pivotal.io>
Rossen Stoyanchev <rstoyanchev@vmware.com> <rstoyanchev@gopivotal.com>
Phillip Webb <pwebb@vmware.com>
Phillip Webb <pwebb@vmware.com> <pwebb@pivotal.io>
Phillip Webb <pwebb@vmware.com> <pwebb@gopivotal.com>
Chris Beams <cbeams@vmware.com>
Chris Beams <cbeams@vmware.com> <cbeams@pivotal.io>
Chris Beams <cbeams@vmware.com> <cbeams@gopivotal.com>
Arjen Poutsma <poutsmaa@vmware.com>
Arjen Poutsma <poutsmaa@vmware.com> <apoutsma@pivotal.io>
Arjen Poutsma <poutsmaa@vmware.com> <apoutsma@gopivotal.com>
Arjen Poutsma <poutsmaa@vmware.com> <poutsma@mac.com>
Arjen Poutsma <poutsmaa@vmware.com> <apoutsma@vmware.com>
Oliver Drotbohm <odrotbohm@vmware.com>
Oliver Drotbohm <odrotbohm@vmware.com> <ogierke@vmware.com>
Oliver Drotbohm <odrotbohm@vmware.com> <ogierke@pivotal.io>
Oliver Drotbohm <odrotbohm@vmware.com> <ogierke@gopivotal.com>
Dave Syer <dsyer@vmware.com>
Dave Syer <dsyer@vmware.com> <dsyer@pivotal.io>
Dave Syer <dsyer@vmware.com> <dsyer@gopivotal.com>
Dave Syer <dsyer@vmware.com> <david_syer@hotmail.com>
Andy Clement <aclement@vmware.com>
Andy Clement <aclement@vmware.com> <aclement@pivotal.io>
Andy Clement <aclement@vmware.com> <aclement@gopivotal.com>
Andy Clement <aclement@vmware.com> <andrew.clement@gmail.com>
Sam Brannen <sbrannen@vmware.com>
Sam Brannen <sbrannen@vmware.com> <sbrannen@pivotal.io>
Sam Brannen <sbrannen@vmware.com> <sam@sambrannen.com>
Simon Basle <sbasle@vmware.com>
Simon Baslé <sbasle@vmware.com>
<dmitry.katsubo@gmail.com> <dmitry.katsubo@gmai.com>
Nick Williams <nicholas@nicholaswilliams.net>
+1 -1
View File
@@ -1,3 +1,3 @@
# Enable auto-env through the sdkman_auto_env config
# Add key=value pairs of SDKs to use below
java=17.0.8.1-librca
java=17.0.10-librca
+2 -2
View File
@@ -1,4 +1,4 @@
# <img src="framework-docs/src/docs/spring-framework.png" width="80" height="80"> Spring Framework [![Build Status](https://ci.spring.io/api/v1/teams/spring-framework/pipelines/spring-framework-6.0.x/jobs/build/badge)](https://ci.spring.io/teams/spring-framework/pipelines/spring-framework-6.0.x?groups=Build") [![Revved up by Gradle Enterprise](https://img.shields.io/badge/Revved%20up%20by-Gradle%20Enterprise-06A0CE?logo=Gradle&labelColor=02303A)](https://ge.spring.io/scans?search.rootProjectNames=spring)
# <img src="framework-docs/src/docs/spring-framework.png" width="80" height="80"> Spring Framework [![Build Status](https://ci.spring.io/api/v1/teams/spring-framework/pipelines/spring-framework-6.1.x/jobs/build/badge)](https://ci.spring.io/teams/spring-framework/pipelines/spring-framework-6.1.x?groups=Build") [![Revved up by Develocity](https://img.shields.io/badge/Revved%20up%20by-Develocity-06A0CE?logo=Gradle&labelColor=02303A)](https://ge.spring.io/scans?search.rootProjectNames=spring)
This is the home of the Spring Framework: the foundation for all [Spring projects](https://spring.io/projects). Collectively the Spring Framework and the family of Spring projects are often referred to simply as "Spring".
@@ -31,7 +31,7 @@ Information regarding CI builds can be found in the [Spring Framework Concourse
## Stay in Touch
Follow [@SpringCentral](https://twitter.com/springcentral), [@SpringFramework](https://twitter.com/springframework), and its [team members](https://twitter.com/springframework/lists/team/members) on Twitter. In-depth articles can be found at [The Spring Blog](https://spring.io/blog/), and releases are announced via our [releases feed](https://spring.io/blog/category/releases).
Follow [@SpringCentral](https://twitter.com/springcentral), [@SpringFramework](https://twitter.com/springframework), and its [team members](https://twitter.com/springframework/lists/team/members) on 𝕏. In-depth articles can be found at [The Spring Blog](https://spring.io/blog/), and releases are announced via our [releases feed](https://spring.io/blog/category/releases).
## License
+4 -7
View File
@@ -4,7 +4,7 @@ plugins {
id 'org.jetbrains.kotlin.plugin.serialization' version "${kotlinVersion}" apply false
id 'org.jetbrains.dokka' version '1.8.20'
id 'org.unbroken-dome.xjc' version '2.0.0' apply false
id 'com.github.ben-manes.versions' version '0.49.0'
id 'com.github.ben-manes.versions' version '0.51.0'
id 'com.github.johnrengelman.shadow' version '8.1.1' apply false
id 'de.undercouch.download' version '5.4.0'
id 'me.champeau.jmh' version '0.7.2' apply false
@@ -16,6 +16,8 @@ ext {
javaProjects = subprojects.findAll { !it.name.startsWith("framework-") }
}
description = "Spring Framework"
configure(allprojects) { project ->
apply plugin: "org.springframework.build.localdev"
group = "org.springframework"
@@ -102,7 +104,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.10.1/api/",
// "https://junit.org/junit5/docs/5.10.2/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/",
@@ -116,8 +118,3 @@ configure([rootProject] + javaProjects) { project ->
configure(moduleProjects) { project ->
apply from: "${rootDir}/gradle/spring-module.gradle"
}
configure(rootProject) {
description = "Spring Framework"
apply plugin: 'org.springframework.build.api-diff'
}
-15
View File
@@ -22,21 +22,6 @@ but doesn't affect the classpath of dependent projects.
This plugin does not provide a `provided` configuration, as the native `compileOnly` and `testCompileOnly`
configurations are preferred.
### API Diff
This plugin uses the [Gradle JApiCmp](https://github.com/melix/japicmp-gradle-plugin) plugin
to generate API Diff reports for each Spring Framework module. This plugin is applied once on the root
project and creates tasks in each framework module. Unlike previous versions of this part of the build,
there is no need for checking out a specific tag. The plugin will fetch the JARs we want to compare the
current working version with. You can generate the reports for all modules or a single module:
```
./gradlew apiDiff -PbaselineVersion=5.1.0.RELEASE
./gradlew :spring-core:apiDiff -PbaselineVersion=5.1.0.RELEASE
```
The reports are located under `build/reports/api-diff/$OLDVERSION_to_$NEWVERSION/`.
### RuntimeHints Java Agent
+1 -6
View File
@@ -21,18 +21,13 @@ dependencies {
checkstyle "io.spring.javaformat:spring-javaformat-checkstyle:${javaFormatVersion}"
implementation "org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}"
implementation "org.jetbrains.kotlin:kotlin-compiler-embeddable:${kotlinVersion}"
implementation "me.champeau.gradle:japicmp-gradle-plugin:0.3.0"
implementation "org.gradle:test-retry-gradle-plugin:1.4.1"
implementation "org.gradle:test-retry-gradle-plugin:1.5.6"
implementation "io.spring.javaformat:spring-javaformat-gradle-plugin:${javaFormatVersion}"
implementation "io.spring.nohttp:nohttp-gradle:0.0.11"
}
gradlePlugin {
plugins {
apiDiffPlugin {
id = "org.springframework.build.api-diff"
implementationClass = "org.springframework.build.api.ApiDiffPlugin"
}
conventionsPlugin {
id = "org.springframework.build.conventions"
implementationClass = "org.springframework.build.ConventionsPlugin"
+1 -1
View File
@@ -1,2 +1,2 @@
org.gradle.caching=true
javaFormatVersion=0.0.39
javaFormatVersion=0.0.41
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -50,12 +50,12 @@ public class CheckstyleConventions {
project.getPlugins().apply(CheckstylePlugin.class);
project.getTasks().withType(Checkstyle.class).forEach(checkstyle -> checkstyle.getMaxHeapSize().set("1g"));
CheckstyleExtension checkstyle = project.getExtensions().getByType(CheckstyleExtension.class);
checkstyle.setToolVersion("10.12.5");
checkstyle.setToolVersion("10.14.1");
checkstyle.getConfigDirectory().set(project.getRootProject().file("src/checkstyle"));
String version = SpringJavaFormatPlugin.class.getPackage().getImplementationVersion();
DependencySet checkstyleDependencies = project.getConfigurations().getByName("checkstyle").getDependencies();
checkstyleDependencies
.add(project.getDependencies().create("io.spring.javaformat:spring-javaformat-checkstyle:" + version));
checkstyleDependencies.add(
project.getDependencies().create("io.spring.javaformat:spring-javaformat-checkstyle:" + version));
});
}
@@ -1,142 +0,0 @@
/*
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.build.api;
import java.io.File;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import me.champeau.gradle.japicmp.JapicmpPlugin;
import me.champeau.gradle.japicmp.JapicmpTask;
import org.gradle.api.GradleException;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.plugins.JavaBasePlugin;
import org.gradle.api.plugins.JavaPlugin;
import org.gradle.api.publish.maven.plugins.MavenPublishPlugin;
import org.gradle.api.tasks.TaskProvider;
import org.gradle.jvm.tasks.Jar;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* {@link Plugin} that applies the {@code "japicmp-gradle-plugin"}
* and create tasks for all subprojects named {@code "spring-*"}, diffing the public API one by one
* and creating the reports in {@code "build/reports/api-diff/$OLDVERSION_to_$NEWVERSION/"}.
* <p>{@code "./gradlew apiDiff -PbaselineVersion=5.1.0.RELEASE"} will output the
* reports for the API diff between the baseline version and the current one for all modules.
* You can limit the report to a single module with
* {@code "./gradlew :spring-core:apiDiff -PbaselineVersion=5.1.0.RELEASE"}.
*
* @author Brian Clozel
*/
public class ApiDiffPlugin implements Plugin<Project> {
private static final Logger logger = LoggerFactory.getLogger(ApiDiffPlugin.class);
public static final String TASK_NAME = "apiDiff";
private static final String BASELINE_VERSION_PROPERTY = "baselineVersion";
private static final List<String> PACKAGE_INCLUDES = Collections.singletonList("org.springframework.*");
private static final URI SPRING_MILESTONE_REPOSITORY = URI.create("https://repo.spring.io/milestone");
@Override
public void apply(Project project) {
if (project.hasProperty(BASELINE_VERSION_PROPERTY) && project.equals(project.getRootProject())) {
project.getPluginManager().apply(JapicmpPlugin.class);
project.getPlugins().withType(JapicmpPlugin.class,
plugin -> applyApiDiffConventions(project));
}
}
private void applyApiDiffConventions(Project project) {
String baselineVersion = project.property(BASELINE_VERSION_PROPERTY).toString();
project.subprojects(subProject -> {
if (subProject.getName().startsWith("spring-")) {
createApiDiffTask(baselineVersion, subProject);
}
});
}
private void createApiDiffTask(String baselineVersion, Project project) {
if (isProjectEligible(project)) {
// Add Spring Milestone repository for generating diffs against previous milestones
project.getRootProject()
.getRepositories()
.maven(mavenArtifactRepository -> mavenArtifactRepository.setUrl(SPRING_MILESTONE_REPOSITORY));
JapicmpTask apiDiff = project.getTasks().create(TASK_NAME, JapicmpTask.class);
apiDiff.setDescription("Generates an API diff report with japicmp");
apiDiff.setGroup(JavaBasePlugin.DOCUMENTATION_GROUP);
apiDiff.setOldClasspath(createBaselineConfiguration(baselineVersion, project));
TaskProvider<Jar> jar = project.getTasks().withType(Jar.class).named("jar");
apiDiff.setNewArchives(project.getLayout().files(jar.get().getArchiveFile().get().getAsFile()));
apiDiff.setNewClasspath(getRuntimeClassPath(project));
apiDiff.setPackageIncludes(PACKAGE_INCLUDES);
apiDiff.setOnlyModified(true);
apiDiff.setIgnoreMissingClasses(true);
// Ignore Kotlin metadata annotations since they contain
// illegal HTML characters and fail the report generation
apiDiff.setAnnotationExcludes(Collections.singletonList("@kotlin.Metadata"));
apiDiff.setHtmlOutputFile(getOutputFile(baselineVersion, project));
apiDiff.dependsOn(project.getTasks().getByName("jar"));
}
}
private boolean isProjectEligible(Project project) {
return project.getPlugins().hasPlugin(JavaPlugin.class)
&& project.getPlugins().hasPlugin(MavenPublishPlugin.class);
}
private Configuration createBaselineConfiguration(String baselineVersion, Project project) {
String baseline = String.join(":",
project.getGroup().toString(), project.getName(), baselineVersion);
Dependency baselineDependency = project.getDependencies().create(baseline + "@jar");
Configuration baselineConfiguration = project.getRootProject().getConfigurations().detachedConfiguration(baselineDependency);
try {
// eagerly resolve the baseline configuration to check whether this is a new Spring module
baselineConfiguration.resolve();
return baselineConfiguration;
}
catch (GradleException exception) {
logger.warn("Could not resolve {} - assuming this is a new Spring module.", baseline);
}
return project.getRootProject().getConfigurations().detachedConfiguration();
}
private Configuration getRuntimeClassPath(Project project) {
return project.getConfigurations().getByName(JavaPlugin.RUNTIME_CLASSPATH_CONFIGURATION_NAME);
}
private File getOutputFile(String baseLineVersion, Project project) {
String buildDirectoryPath = project.getRootProject()
.getLayout().getBuildDirectory().getAsFile().get().getAbsolutePath();
Path outDir = Paths.get(buildDirectoryPath, "reports", "api-diff",
baseLineVersion + "_to_" + project.getRootProject().getVersion());
return project.file(outDir.resolve(project.getName() + ".html").toString());
}
}
+2 -2
View File
@@ -2,7 +2,7 @@
The Spring Framework uses https://concourse-ci.org/[Concourse] for its CI build and other automated tasks.
The Spring team has a dedicated Concourse instance available at https://ci.spring.io with a build pipeline
for https://ci.spring.io/teams/spring-framework/pipelines/spring-framework-6.0.x[Spring Framework 6.0.x].
for https://ci.spring.io/teams/spring-framework/pipelines/spring-framework-6.1.x[Spring Framework 6.1.x].
=== Setting up your development environment
@@ -51,7 +51,7 @@ The pipeline can be deployed using the following command:
[source]
----
$ fly -t spring set-pipeline -p spring-framework-6.0.x -c ci/pipeline.yml -l ci/parameters.yml
$ fly -t spring set-pipeline -p spring-framework-6.1.x -c ci/pipeline.yml -l ci/parameters.yml
----
NOTE: This assumes that you have credhub integration configured with the appropriate secrets.
+2 -2
View File
@@ -1,4 +1,4 @@
FROM ubuntu:jammy-20231004
FROM ubuntu:jammy-20240125
ADD setup.sh /setup.sh
ADD get-jdk-url.sh /get-jdk-url.sh
@@ -7,6 +7,6 @@ RUN ./setup.sh
ENV JAVA_HOME /opt/openjdk/java17
ENV JDK17 /opt/openjdk/java17
ENV JDK21 /opt/openjdk/java21
ENV JDK22 /opt/openjdk/java22
ENV JDK23 /opt/openjdk/java23
ENV PATH $JAVA_HOME/bin:$PATH
+4 -4
View File
@@ -3,13 +3,13 @@ set -e
case "$1" in
java17)
echo "https://download.bell-sw.com/java/17.0.9+11/bellsoft-jdk17.0.9+11-linux-amd64.tar.gz"
echo "https://github.com/bell-sw/Liberica/releases/download/17.0.10%2B13/bellsoft-jdk17.0.10+13-linux-amd64.tar.gz"
;;
java21)
echo "https://download.bell-sw.com/java/21.0.1+12/bellsoft-jdk21.0.1+12-linux-amd64.tar.gz"
echo "https://github.com/bell-sw/Liberica/releases/download/21.0.2%2B14/bellsoft-jdk21.0.2+14-linux-amd64.tar.gz"
;;
java22)
echo "https://download.java.net/java/early_access/jdk22/19/GPL/openjdk-22-ea+19_linux-x64_bin.tar.gz"
java23)
echo "https://download.java.net/java/early_access/jdk23/10/GPL/openjdk-23-ea+10_linux-x64_bin.tar.gz"
;;
*)
echo $"Unknown java version"
+1 -1
View File
@@ -3,7 +3,7 @@ github-repo-name: "spring-projects/spring-framework"
sonatype-staging-profile: "org.springframework"
docker-hub-organization: "springci"
artifactory-server: "https://repo.spring.io"
branch: "main"
branch: "6.1.x"
milestone: "6.1.x"
build-name: "spring-framework"
pipeline-name: "spring-framework"
+10 -8
View File
@@ -121,14 +121,14 @@ resources:
access_token: ((github-ci-status-token))
branch: ((branch))
context: jdk21-build
- name: repo-status-jdk22-build
- name: repo-status-jdk23-build
type: github-status-resource
icon: eye-check-outline
source:
repository: ((github-repo-name))
access_token: ((github-ci-status-token))
branch: ((branch))
context: jdk22-build
context: jdk23-build
- name: slack-alert
type: slack-notification
icon: slack
@@ -249,13 +249,15 @@ jobs:
<<: *slack-fail-params
- put: repo-status-jdk21-build
params: { state: "success", commit: "git-repo" }
- name: jdk22-build
- name: jdk23-build
serial: true
public: true
plan:
- get: ci-image
- get: git-repo
- put: repo-status-jdk22-build
- get: every-morning
trigger: false
- put: repo-status-jdk23-build
params: { state: "pending", commit: "git-repo" }
- do:
- task: check-project
@@ -264,16 +266,16 @@ jobs:
privileged: true
timeout: ((task-timeout))
params:
TEST_TOOLCHAIN: 22
TEST_TOOLCHAIN: 23
<<: *build-project-task-params
on_failure:
do:
- put: repo-status-jdk22-build
- put: repo-status-jdk23-build
params: { state: "failure", commit: "git-repo" }
- put: slack-alert
params:
<<: *slack-fail-params
- put: repo-status-jdk22-build
- put: repo-status-jdk23-build
params: { state: "success", commit: "git-repo" }
- name: stage-milestone
serial: true
@@ -426,7 +428,7 @@ jobs:
groups:
- name: "builds"
jobs: ["build", "jdk21-build", "jdk22-build"]
jobs: ["build", "jdk21-build", "jdk23-build"]
- name: "releases"
jobs: ["stage-milestone", "stage-rc", "stage-release", "promote-milestone", "promote-rc", "promote-release", "create-github-release"]
- name: "ci-images"
+1 -1
View File
@@ -5,6 +5,6 @@ source $(dirname $0)/common.sh
repository=$(pwd)/distribution-repository
pushd git-repo > /dev/null
./gradlew -Dorg.gradle.internal.launcher.welcomeMessageEnabled=false -Porg.gradle.java.installations.fromEnv=JDK17,JDK21,JDK22 \
./gradlew -Dorg.gradle.internal.launcher.welcomeMessageEnabled=false -Porg.gradle.java.installations.fromEnv=JDK17,JDK21,JDK23 \
--no-daemon --max-workers=4 -PdeploymentRepository=${repository} build publishAllPublicationsToDeploymentRepository
popd > /dev/null
+1 -1
View File
@@ -4,6 +4,6 @@ set -e
source $(dirname $0)/common.sh
pushd git-repo > /dev/null
./gradlew -Dorg.gradle.internal.launcher.welcomeMessageEnabled=false -Porg.gradle.java.installations.fromEnv=JDK17,JDK21 \
./gradlew -Dorg.gradle.internal.launcher.welcomeMessageEnabled=false -Porg.gradle.java.installations.fromEnv=JDK17,JDK21,JDK23 \
-PmainToolchain=${MAIN_TOOLCHAIN} -PtestToolchain=${TEST_TOOLCHAIN} --no-daemon --max-workers=4 check antora
popd > /dev/null
+3 -3
View File
@@ -27,8 +27,8 @@ javadoc {
author = true
header = rootProject.description
use = true
overview = "$rootProject.rootDir/framework-docs/src/docs/api/overview.html"
destinationDir = file("${project.buildDir}/docs/javadoc-api")
overview = project.relativePath("$rootProject.rootDir/framework-docs/src/docs/api/overview.html")
destinationDir = file("$project.docsDir/javadoc-api")
splitIndex = true
links(rootProject.ext.javadocLinks)
addBooleanOption('Xdoclint:syntax,reference', true) // only check syntax and reference with doclint
@@ -52,7 +52,7 @@ rootProject.tasks.dokkaHtmlMultiModule.configure {
tasks.named("javadoc")
}
moduleName.set("spring-framework")
outputDirectory.set(project.file("$buildDir/docs/kdoc-api"))
outputDirectory.set(file("$docsDir/kdoc-api"))
includes.from("$rootProject.rootDir/framework-docs/src/docs/api/dokka-overview.md")
}
+1
View File
@@ -18,6 +18,7 @@ asciidoc:
# FIXME: The package is not renamed
chomp: 'all'
fold: 'all'
table-stripes: 'odd'
include-java: 'example$docs-src/main/java/org/springframework/docs'
spring-site: 'https://spring.io'
spring-site-blog: '{spring-site}/blog'
+2 -2
View File
@@ -28,8 +28,8 @@ antora {
'@antora/atlas-extension': '1.0.0-alpha.1',
'@antora/collector-extension': '1.0.0-alpha.3',
'@asciidoctor/tabs': '1.0.0-beta.3',
'@opendevise/antora-release-line-extension': '1.0.0-alpha.2',
'@springio/antora-extensions': '1.3.0',
'@opendevise/antora-release-line-extension': '1.0.0',
'@springio/antora-extensions': '1.8.2',
'@springio/asciidoctor-extensions': '1.0.0-alpha.9'
]
}
+4 -3
View File
@@ -39,8 +39,8 @@
** xref:core/resources.adoc[]
** xref:core/validation.adoc[]
*** xref:core/validation/validator.adoc[]
*** xref:core/validation/conversion.adoc[]
*** xref:core/validation/beans-beans.adoc[]
*** xref:core/validation/conversion.adoc[]
*** xref:core/validation/convert.adoc[]
*** xref:core/validation/format.adoc[]
*** xref:core/validation/format-configuring-formatting-globaldatetimeformat.adoc[]
@@ -421,7 +421,7 @@
*** xref:integration/cache/specific-config.adoc[]
** xref:integration/observability.adoc[]
** xref:integration/checkpoint-restore.adoc[]
** xref:integration/class-data-sharing.adoc[]
** xref:integration/cds.adoc[]
** xref:integration/appendix.adoc[]
* xref:languages.adoc[]
** xref:languages/kotlin.adoc[]
@@ -439,4 +439,5 @@
** xref:languages/groovy.adoc[]
** xref:languages/dynamic.adoc[]
* xref:appendix.adoc[]
* {spring-framework-wiki}[Wiki]
* {spring-framework-wiki}[Wiki]
@@ -19,15 +19,53 @@ of the classpath -- for example, deployed within the application's JAR file.
The following table lists all currently supported Spring properties.
.Supported Spring Properties
[cols="1,1"]
|===
| Name | Description
| `spring.aot.enabled`
| Indicates the application should run with AOT generated artifacts. See
xref:core/aot.adoc[Ahead of Time Optimizations] and
{spring-framework-api}++/aot/AotDetector.html#AOT_ENABLED++[`AotDetector`]
for details.
| `spring.beaninfo.ignore`
| Instructs Spring to use the `Introspector.IGNORE_ALL_BEANINFO` mode when calling the
JavaBeans `Introspector`. See
{spring-framework-api}++/beans/StandardBeanInfoFactory.html#IGNORE_BEANINFO_PROPERTY_NAME++[`CachedIntrospectionResults`]
for details.
| `spring.cache.reactivestreams.ignore`
| Instructs Spring's caching infrastructure to ignore the presence of Reactive Streams,
in particular Reactor's `Mono`/`Flux` in `@Cacheable` method return type declarations. See
{spring-framework-api}++/cache/interceptor/CacheAspectSupport.html#IGNORE_REACTIVESTREAMS_PROPERTY_NAME++[`CacheAspectSupport`]
for details.
| `spring.classformat.ignore`
| Instructs Spring to ignore class format exceptions during classpath scanning, in
particular for unsupported class file versions. See
{spring-framework-api}++/context/annotation/ClassPathScanningCandidateComponentProvider.html#IGNORE_CLASSFORMAT_PROPERTY_NAME++[`ClassPathScanningCandidateComponentProvider`]
for details.
| `spring.context.checkpoint`
| Property that specifies a common context checkpoint. See
xref:integration/checkpoint-restore.adoc#_automatic_checkpointrestore_at_startup[Automatic
checkpoint/restore at startup] and
{spring-framework-api}++/context/support/DefaultLifecycleProcessor.html#CHECKPOINT_PROPERTY_NAME++[`DefaultLifecycleProcessor`]
for details.
| `spring.context.exit`
| Property for terminating the JVM when the context reaches a specific phase. See
xref:integration/checkpoint-restore.adoc#_automatic_checkpointrestore_at_startup[Automatic
checkpoint/restore at startup] and
{spring-framework-api}++/context/support/DefaultLifecycleProcessor.html#EXIT_PROPERTY_NAME++[`DefaultLifecycleProcessor`]
for details.
| `spring.context.expression.maxLength`
| The maximum length for
xref:core/expressions/evaluation.adoc#expressions-parser-configuration[Spring Expression Language]
expressions used in XML bean definitions, `@Value`, etc.
| `spring.expression.compiler.mode`
| The mode to use when compiling expressions for the
xref:core/expressions/evaluation.adoc#expressions-compiler-configuration[Spring Expression Language].
@@ -291,6 +291,8 @@ to consider:
* `final` classes cannot be proxied, because they cannot be extended.
* `final` methods cannot be advised, because they cannot be overridden.
* `private` methods cannot be advised, because they cannot be overridden.
* Methods that are not visible, typically package private methods in a parent class
from a different package, cannot be advised because they are effectively private.
NOTE: There is no need to add CGLIB to your classpath. CGLIB is repackaged and included
in the `spring-core` JAR. In other words, CGLIB-based AOP works "out of the box", as do
@@ -168,7 +168,7 @@ Kotlin::
======
NOTE: Pooling stateless service objects is not usually necessary. We do not believe it should
be the default choice, as most stateless objects are naturally thread safe, and instance
be the default choice, as most stateless objects are naturally thread-safe, and instance
pooling is problematic if resources are cached.
Simpler pooling is available by using auto-proxying. You can set the `TargetSource` implementations
@@ -521,8 +521,8 @@ standard AspectJ. The following example shows the `aop.xml` file:
<aspectj>
<weaver>
<!-- only weave classes in our application-specific packages -->
<include within="com.xyz.*"/>
<!-- only weave classes in our application-specific packages and sub-packages -->
<include within="com.xyz..*"/>
</weaver>
<aspects>
@@ -533,6 +533,11 @@ standard AspectJ. The following example shows the `aop.xml` file:
</aspectj>
----
NOTE: It is recommended to only weave specific classes (typically those in the
application packages, as shown in the `aop.xml` example above) in order
to avoid side effects such as AspectJ dump files and warnings.
This is also a best practice from an efficiency perspective.
Now we can move on to the Spring-specific portion of the configuration. We need
to configure a `LoadTimeWeaver` (explained later). This load-time weaver is the
essential component responsible for weaving the aspect configuration in one or
@@ -714,10 +719,29 @@ Furthermore, the compiled aspect classes need to be available on the classpath.
[[aop-aj-ltw-aop_dot_xml]]
=== 'META-INF/aop.xml'
=== `META-INF/aop.xml`
The AspectJ LTW infrastructure is configured by using one or more `META-INF/aop.xml`
files that are on the Java classpath (either directly or, more typically, in jar files).
For example:
[source,xml,indent=0,subs="verbatim"]
----
<!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "https://www.eclipse.org/aspectj/dtd/aspectj.dtd">
<aspectj>
<weaver>
<!-- only weave classes in our application-specific packages and sub-packages -->
<include within="com.xyz..*"/>
</weaver>
</aspectj>
----
NOTE: It is recommended to only weave specific classes (typically those in the
application packages, as shown in the `aop.xml` example above) in order
to avoid side effects such as AspectJ dump files and warnings.
This is also a best practice from an efficiency perspective.
The structure and contents of this file is detailed in the LTW part of the
{aspectj-docs-devguide}/ltw-configuration.html[AspectJ reference
+52 -15
View File
@@ -17,8 +17,11 @@ Applying such optimizations early implies the following restrictions:
* The beans defined in your application cannot change at runtime, meaning:
** `@Profile`, in particular profile-specific configuration needs to be chosen at build time.
** `Environment` properties that impact the presence of a bean (`@Conditional`) are only considered at build time.
* Bean definitions with instance suppliers (lambdas or method references) cannot be transformed ahead-of-time (see related {spring-framework-issues}/29555[spring-framework#29555] issue).
* Make sure that the bean type is as precise as possible.
* Bean definitions with instance suppliers (lambdas or method references) cannot be transformed ahead-of-time.
* Beans registered as singletons (using `registerSingleton`, typically from
`ConfigurableListableBeanFactory`) cannot be transformed ahead-of-time either.
* As we cannot rely on the instance, make sure that the bean type is as precise as
possible.
TIP: See also the xref:core/aot.adoc#aot.bestpractices[] section.
@@ -27,7 +30,7 @@ A Spring AOT processed application typically generates:
* Java source code
* Bytecode (usually for dynamic proxies)
* {spring-framework-api}/aot/hint/RuntimeHints.html[`RuntimeHints`] for the use of reflection, resource loading, serialization, and JDK proxies.
* {spring-framework-api}/aot/hint/RuntimeHints.html[`RuntimeHints`] for the use of reflection, resource loading, serialization, and JDK proxies
NOTE: At the moment, AOT is focused on allowing Spring applications to be deployed as native images using GraalVM.
We intend to support more JVM-based use cases in future generations.
@@ -35,7 +38,7 @@ We intend to support more JVM-based use cases in future generations.
[[aot.basics]]
== AOT engine overview
The entry point of the AOT engine for processing an `ApplicationContext` arrangement is `ApplicationContextAotGenerator`. It takes care of the following steps, based on a `GenericApplicationContext` that represents the application to optimize and a {spring-framework-api}/aot/generate/GenerationContext.html[`GenerationContext`]:
The entry point of the AOT engine for processing an `ApplicationContext` is `ApplicationContextAotGenerator`. It takes care of the following steps, based on a `GenericApplicationContext` that represents the application to optimize and a {spring-framework-api}/aot/generate/GenerationContext.html[`GenerationContext`]:
* Refresh an `ApplicationContext` for AOT processing. Contrary to a traditional refresh, this version only creates bean definitions, not bean instances.
* Invoke the available `BeanFactoryInitializationAotProcessor` implementations and apply their contributions against the `GenerationContext`.
@@ -67,7 +70,14 @@ include-code::./AotProcessingSample[tag=aotcontext]
In this mode, xref:core/beans/factory-extension.adoc#beans-factory-extension-factory-postprocessors[`BeanFactoryPostProcessor` implementations] are invoked as usual.
This includes configuration class parsing, import selectors, classpath scanning, etc.
Such steps make sure that the `BeanRegistry` contains the relevant bean definitions for the application.
If bean definitions are guarded by conditions (such as `@Profile`), these are discarded at this stage.
If bean definitions are guarded by conditions (such as `@Profile`), these are evaluated,
and bean definitions that don't match their conditions are discarded at this stage.
If custom code needs to register extra beans programmatically, make sure that custom
registration code uses `BeanDefinitionRegistry` instead of `BeanFactory` as only bean
definitions are taken into account. A good pattern is to implement
`ImportBeanDefinitionRegistrar` and register it via an `@Import` on one of your
configuration classes.
Because this mode does not actually create bean instances, `BeanPostProcessor` implementations are not invoked, except for specific variants that are relevant for AOT processing.
These are:
@@ -84,12 +94,12 @@ Once this part completes, the `BeanFactory` contains the bean definitions that a
Components that want to participate in this step can implement the {spring-framework-api}/beans/factory/aot/BeanFactoryInitializationAotProcessor.html[`BeanFactoryInitializationAotProcessor`] interface.
Each implementation can return an AOT contribution, based on the state of the bean factory.
An AOT contribution is a component that contributes generated code that reproduces a particular behavior.
An AOT contribution is a component that contributes generated code which reproduces a particular behavior.
It can also contribute `RuntimeHints` to indicate the need for reflection, resource loading, serialization, or JDK proxies.
A `BeanFactoryInitializationAotProcessor` implementation can be registered in `META-INF/spring/aot.factories` with a key equal to the fully qualified name of the interface.
A `BeanFactoryInitializationAotProcessor` implementation can be registered in `META-INF/spring/aot.factories` with a key equal to the fully-qualified name of the interface.
A `BeanFactoryInitializationAotProcessor` can also be implemented directly by a bean.
The `BeanFactoryInitializationAotProcessor` interface can also be implemented directly by a bean.
In this mode, the bean provides an AOT contribution equivalent to the feature it provides with a regular runtime.
Consequently, such a bean is automatically excluded from the AOT-optimized context.
@@ -111,7 +121,7 @@ This interface is used as follows:
* Implemented by a `BeanPostProcessor` bean, to replace its runtime behavior.
For instance xref:core/beans/factory-extension.adoc#beans-factory-extension-bpp-examples-aabpp[`AutowiredAnnotationBeanPostProcessor`] implements this interface to generate code that injects members annotated with `@Autowired`.
* Implemented by a type registered in `META-INF/spring/aot.factories` with a key equal to the fully qualified name of the interface.
* Implemented by a type registered in `META-INF/spring/aot.factories` with a key equal to the fully-qualified name of the interface.
Typically used when the bean definition needs to be tuned for specific features of the core framework.
[NOTE]
@@ -156,6 +166,7 @@ Java::
/**
* Bean definitions for {@link DataSourceConfiguration}
*/
@Generated
public class DataSourceConfiguration__BeanDefinitions {
/**
* Get the bean definition for 'dataSourceConfiguration'
@@ -190,6 +201,9 @@ Java::
NOTE: The exact code generated may differ depending on the exact nature of your bean definitions.
TIP: Each generated class is annotated with `org.springframework.aot.generate.Generated` to
identify them if they need to be excluded, for instance by static analysis tools.
The generated code above creates bean definitions equivalent to the `@Configuration` class, but in a direct way and without the use of reflection if at all possible.
There is a bean definition for `dataSourceConfiguration` and one for `dataSourceBean`.
When a `datasource` instance is required, a `BeanInstanceSupplier` is called.
@@ -203,11 +217,33 @@ However, keep in mind that some optimizations are made at build time based on a
This section lists the best practices that make sure your application is ready for AOT.
[[aot.bestpractices.bean-registration]]
== Programmatic bean registration
The AOT engine takes care of the `@Configuration` model and any callback that might be
invoked as part of processing your configuration. If you need to register additional
beans programmatically, make sure to use a `BeanDefinitionRegistry` to register
bean definitions.
This can typically be done via a `BeanDefinitionRegistryPostProcessor`. Note that, if it
is registered itself as a bean, it will be invoked again at runtime unless you make
sure to implement `BeanFactoryInitializationAotProcessor` as well. A more idiomatic
way is to implement `ImportBeanDefinitionRegistrar` and register it using `@Import` on
one of your configuration classes. This invokes your custom code as part of configuration
class parsing.
If you declare additional beans programmatically using a different callback, they are
likely not going to be handled by the AOT engine, and therefore no hints are going to be
generated for them. Depending on the environment, those beans may not be registered at
all. For instance, classpath scanning does not work in a native image as there is no
notion of a classpath. For cases like this, it is crucial that the scanning happens at
build time.
[[aot.bestpractices.bean-type]]
=== Expose The Most Precise Bean Type
While your application may interact with an interface that a bean implements, it is still very important to declare the most precise type.
The AOT engine performs additional checks on the bean type, such as detecting the presence of `@Autowired` members, or lifecycle callback methods.
The AOT engine performs additional checks on the bean type, such as detecting the presence of `@Autowired` members or lifecycle callback methods.
For `@Configuration` classes, make sure that the return type of the factory `@Bean` method is as precise as possible.
Consider the following example:
@@ -258,10 +294,11 @@ If you are registering bean definitions programmatically, consider using `RootBe
[[aot.bestpractices.constructors]]
=== Avoid Multiple Constructors
The container is able to choose the most appropriate constructor to use based on several candidates.
However, this is not a best practice and flagging the preferred constructor with `@Autowired` if necessary is preferred.
In case you are working on a code base that you can't modify, you can set the {spring-framework-api}/beans/factory/support/AbstractBeanDefinition.html#PREFERRED_CONSTRUCTORS_ATTRIBUTE[`preferredConstructors` attribute] on the related bean definition to indicate which constructor should be used.
In case you are working on a code base that you cannot modify, you can set the {spring-framework-api}/beans/factory/support/AbstractBeanDefinition.html#PREFERRED_CONSTRUCTORS_ATTRIBUTE[`preferredConstructors` attribute] on the related bean definition to indicate which constructor should be used.
[[aot.bestpractices.factory-bean]]
=== FactoryBean
@@ -279,7 +316,7 @@ Java::
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
public class ClientFactoryBean<T extends AbstractClient> implements FactoryBean<T> {
// ...
}
----
======
@@ -376,7 +413,7 @@ Java::
Running an application as a native image requires additional information compared to a regular JVM runtime.
For instance, GraalVM needs to know ahead of time if a component uses reflection.
Similarly, classpath resources are not shipped in a native image unless specified explicitly.
Similarly, classpath resources are not included in a native image unless specified explicitly.
Consequently, if the application needs to load a resource, it must be referenced from the corresponding GraalVM native image configuration file.
The {spring-framework-api}/aot/hint/RuntimeHints.html[`RuntimeHints`] API collects the need for reflection, resource loading, serialization, and JDK proxies at runtime.
@@ -411,7 +448,7 @@ include-code::./SpellCheckService[]
If at all possible, `@ImportRuntimeHints` should be used as close as possible to the component that requires the hints.
This way, if the component is not contributed to the `BeanFactory`, the hints won't be contributed either.
It is also possible to register an implementation statically by adding an entry in `META-INF/spring/aot.factories` with a key equal to the fully qualified name of the `RuntimeHintsRegistrar` interface.
It is also possible to register an implementation statically by adding an entry in `META-INF/spring/aot.factories` with a key equal to the fully-qualified name of the `RuntimeHintsRegistrar` interface.
[[aot.hints.reflective]]
@@ -420,7 +457,7 @@ It is also possible to register an implementation statically by adding an entry
{spring-framework-api}/aot/hint/annotation/Reflective.html[`@Reflective`] provides an idiomatic way to flag the need for reflection on an annotated element.
For instance, `@EventListener` is meta-annotated with `@Reflective` since the underlying implementation invokes the annotated method using reflection.
By default, only Spring beans are considered and an invocation hint is registered for the annotated element.
By default, only Spring beans are considered, and an invocation hint is registered for the annotated element.
This can be tuned by specifying a custom `ReflectiveProcessor` implementation via the
`@Reflective` annotation.
@@ -155,6 +155,8 @@ If there is no other resolution indicator (such as a qualifier or a primary mark
for a non-unique dependency situation, Spring matches the injection point name
(that is, the field name or parameter name) against the target bean names and chooses the
same-named candidate, if any.
Since version 6.1, this requires the `-parameters` Java compiler flag to be present.
====
That said, if you intend to express annotation-driven injection by name, do not
@@ -141,7 +141,7 @@ Kotlin::
====
After you learn about Spring's IoC container, you may want to know more about Spring's
`Resource` abstraction (as described in
xref:web/webflux-webclient/client-builder.adoc#webflux-client-builder-reactor-resources[Resources])
xref:core/resources.adoc[Resources])
which provides a convenient mechanism for reading an InputStream from locations defined
in a URI syntax. In particular, `Resource` paths are used to construct applications contexts,
as described in xref:core/resources.adoc#resources-app-ctx[Application Contexts and Resource Paths].
@@ -516,8 +516,8 @@ as the following example shows:
[[beans-definition-profiles-default]]
=== Default Profile
The default profile represents the profile that is enabled by default. Consider the
following example:
The default profile represents the profile that is enabled if no profile is active. Consider
the following example:
[tabs]
======
@@ -558,9 +558,9 @@ Kotlin::
----
======
If no profile is active, the `dataSource` is created. You can see this
as a way to provide a default definition for one or more beans. If any
profile is enabled, the default profile does not apply.
If xref:#beans-definition-profiles-enable[no profile is active], the `dataSource` is
created. You can see this as a way to provide a default definition for one or more
beans. If any profile is enabled, the default profile does not apply.
The name of the default profile is `default`. You can change the name of
the default profile by using `setDefaultProfiles()` on the `Environment` or,
@@ -592,6 +592,40 @@ Kotlin::
[[beans-factory-thread-safety]]
=== Thread Safety and Visibility
The Spring core container publishes created singleton instances in a thread-safe manner,
guarding access through a singleton lock and guaranteeing visibility in other threads.
As a consequence, application-provided bean classes do not have to be concerned about the
visibility of their initialization state. Regular configuration fields do not have to be
marked as `volatile` as long as they are only mutated during the initialization phase,
providing visibility guarantees similar to `final` even for setter-based configuration
state that is mutable during that initial phase. If such fields get changed after the
bean creation phase and its subsequent initial publication, they need to be declared as
`volatile` or guarded by a common lock whenever accessed.
Note that concurrent access to such configuration state in singleton bean instances,
e.g. for controller instances or repository instances, is perfectly thread-safe after
such safe initial publication from the container side. This includes common singleton
`FactoryBean` instances which are processed within the general singleton lock as well.
For destruction callbacks, the configuration state remains thread-safe but any runtime
state accumulated between initialization and destruction should be kept in thread-safe
structures (or in `volatile` fields for simple cases) as per common Java guidelines.
Deeper `Lifecycle` integration as shown above involves runtime-mutable state such as
a `runnable` field which will have to be declared as `volatile`. While the common
lifecycle callbacks follow a certain order, e.g. a start callback is guaranteed to
only happen after full initialization and a stop callback only after an initial start,
there is a special case with the common stop before destroy arrangement: It is strongly
recommended that the internal state in any such bean also allows for an immediate
destroy callback without a preceding stop since this may happen during an extraordinary
shutdown after a cancelled bootstrap or in case of a stop timeout caused by another bean.
[[beans-factory-aware]]
== `ApplicationContextAware` and `BeanNameAware`
@@ -324,7 +324,6 @@ Kotlin::
[[beans-factory-scopes-application]]
=== Application Scope
@@ -374,7 +373,6 @@ Kotlin::
[[beans-factory-scopes-websocket]]
=== WebSocket Scope
@@ -384,7 +382,6 @@ xref:web/websocket/stomp/scope.adoc[WebSocket scope] for more details.
[[beans-factory-scopes-other-injection]]
=== Scoped Beans as Dependencies
@@ -544,6 +541,19 @@ see xref:core/aop/proxying.adoc[Proxying Mechanisms].
[[beans-factory-scopes-injection]]
=== Injecting Request/Session References Directly
As an alternative to factory scopes, a Spring `WebApplicationContext` also supports
the injection of `HttpServletRequest`, `HttpServletResponse`, `HttpSession`,
`WebRequest` and (if JSF is present) `FacesContext` and `ExternalContext` into
Spring-managed beans, simply through type-based autowiring next to regular injection
points for other beans. Spring generally injects proxies for such request and session
objects which has the advantage of working in singleton beans and serializable beans
as well, similar to scoped proxies for factory-scoped beans.
[[beans-factory-scopes-custom]]
== Custom Scopes
@@ -1,15 +1,15 @@
[[beans-introduction]]
= Introduction to the Spring IoC Container and Beans
This chapter covers the Spring Framework implementation of the Inversion of Control
(IoC) principle. IoC is also known as dependency injection (DI). It is a process whereby
objects define their dependencies (that is, the other objects they work with) only through
constructor arguments, arguments to a factory method, or properties that are set on the
object instance after it is constructed or returned from a factory method. The container
This chapter covers the Spring Framework implementation of the Inversion of Control (IoC)
principle. Dependency injection (DI) is a specialized form of IoC, whereby objects define
their dependencies (that is, the other objects they work with) only through constructor
arguments, arguments to a factory method, or properties that are set on the object
instance after it is constructed or returned from a factory method. The IoC container
then injects those dependencies when it creates the bean. This process is fundamentally
the inverse (hence the name, Inversion of Control) of the bean itself
controlling the instantiation or location of its dependencies by using direct
construction of classes or a mechanism such as the Service Locator pattern.
the inverse (hence the name, Inversion of Control) of the bean itself controlling the
instantiation or location of its dependencies by using direct construction of classes or
a mechanism such as the Service Locator pattern.
The `org.springframework.beans` and `org.springframework.context` packages are the basis
for Spring Framework's IoC container. The
@@ -3,17 +3,5 @@
:page-section-summary-toc: 1
This section covers how to use annotations in your Java code to configure the Spring
container. It includes the following topics:
* xref:core/beans/java/basic-concepts.adoc[Basic Concepts: `@Bean` and `@Configuration`]
* xref:core/beans/java/instantiating-container.adoc[Instantiating the Spring Container by Using `AnnotationConfigApplicationContext`]
* xref:core/beans/java/bean-annotation.adoc[Using the `@Bean` Annotation]
* xref:core/beans/java/configuration-annotation.adoc[Using the `@Configuration` annotation]
* xref:core/beans/java/composing-configuration-classes.adoc[Composing Java-based Configurations]
* xref:core/beans/environment.adoc#beans-definition-profiles[Bean Definition Profiles]
* xref:core/beans/environment.adoc#beans-property-source-abstraction[`PropertySource` Abstraction]
* xref:core/beans/environment.adoc#beans-using-propertysource[Using `@PropertySource`]
* xref:core/beans/environment.adoc#beans-placeholder-resolution-in-statements[Placeholder Resolution in Statements]
container.
@@ -1,10 +1,11 @@
[[expressions]]
= Spring Expression Language (SpEL)
The Spring Expression Language ("`SpEL`" for short) is a powerful expression language that
The Spring Expression Language ("SpEL" for short) is a powerful expression language that
supports querying and manipulating an object graph at runtime. The language syntax is
similar to Unified EL but offers additional features, most notably method invocation and
basic string templating functionality.
similar to the https://jakarta.ee/specifications/expression-language/[Jakarta Expression
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
@@ -33,26 +34,24 @@ populate them are listed at the end of the chapter.
The expression language supports the following functionality:
* Literal expressions
* Boolean and relational operators
* Regular expressions
* Class expressions
* Accessing properties, arrays, lists, and maps
* Method invocation
* Assignment
* Calling constructors
* Bean references
* Array construction
* Inline lists
* Inline maps
* Ternary operator
* Array construction
* Relational operators
* Regular expressions
* Logical operators
* String operators
* Mathematical operators
* Assignment
* Type expressions
* Method invocation
* Constructor invocation
* Variables
* User-defined functions added to the context
* reflective invocation of `Method`
* various cases of `MethodHandle`
* User-defined functions
* Bean references
* Ternary, Elvis, and safe-navigation operators
* Collection projection
* Collection selection
* Templated expressions
@@ -1,12 +1,12 @@
[[expressions-evaluation]]
= Evaluation
This section introduces the simple use of SpEL interfaces and its expression language.
The complete language reference can be found in
This section introduces programmatic use of SpEL's interfaces and its expression language.
The complete language reference can be found in the
xref:core/expressions/language-ref.adoc[Language Reference].
The following code introduces the SpEL API to evaluate the literal string expression,
`Hello World`.
The following code demonstrates how to use the SpEL API to evaluate the literal string
expression, `Hello World`.
[tabs]
======
@@ -18,7 +18,7 @@ Java::
Expression exp = parser.parseExpression("'Hello World'"); // <1>
String message = (String) exp.getValue();
----
<1> The value of the message variable is `'Hello World'`.
<1> The value of the message variable is `"Hello World"`.
Kotlin::
+
@@ -28,24 +28,24 @@ Kotlin::
val exp = parser.parseExpression("'Hello World'") // <1>
val message = exp.value as String
----
<1> The value of the message variable is `'Hello World'`.
<1> The value of the message variable is `"Hello World"`.
======
The SpEL classes and interfaces you are most likely to use are located in the
`org.springframework.expression` package and its sub-packages, such as `spel.support`.
The `ExpressionParser` interface is responsible for parsing an expression string. In
the preceding example, the expression string is a string literal denoted by the surrounding single
quotation marks. The `Expression` interface is responsible for evaluating the previously defined
expression string. Two exceptions that can be thrown, `ParseException` and
`EvaluationException`, when calling `parser.parseExpression` and `exp.getValue`,
respectively.
The `ExpressionParser` interface is responsible for parsing an expression string. In the
preceding example, the expression string is a string literal denoted by the surrounding
single quotation marks. The `Expression` interface is responsible for evaluating the
defined expression string. The two types of exceptions that can be thrown when calling
`parser.parseExpression(...)` and `exp.getValue(...)` are `ParseException` and
`EvaluationException`, respectively.
SpEL supports a wide range of features, such as calling methods, accessing properties,
SpEL supports a wide range of features such as calling methods, accessing properties,
and calling constructors.
In the following example of method invocation, we call the `concat` method on the string literal:
In the following method invocation example, we call the `concat` method on the string
literal, `Hello World`.
[tabs]
======
@@ -57,7 +57,7 @@ Java::
Expression exp = parser.parseExpression("'Hello World'.concat('!')"); // <1>
String message = (String) exp.getValue();
----
<1> The value of `message` is now 'Hello World!'.
<1> The value of `message` is now `"Hello World!"`.
Kotlin::
+
@@ -67,10 +67,11 @@ Kotlin::
val exp = parser.parseExpression("'Hello World'.concat('!')") // <1>
val message = exp.value as String
----
<1> The value of `message` is now 'Hello World!'.
<1> The value of `message` is now `"Hello World!"`.
======
The following example of calling a JavaBean property calls the `String` property `Bytes`:
The following example demonstrates how to access the `Bytes` JavaBean property of the
string literal, `Hello World`.
[tabs]
======
@@ -100,10 +101,10 @@ Kotlin::
======
SpEL also supports nested properties by using the standard dot notation (such as
`prop1.prop2.prop3`) and also the corresponding setting of property values.
`prop1.prop2.prop3`) as well as the corresponding setting of property values.
Public fields may also be accessed.
The following example shows how to use dot notation to get the length of a literal:
The following example shows how to use dot notation to get the length of a string literal.
[tabs]
======
@@ -133,7 +134,7 @@ Kotlin::
======
The String's constructor can be called instead of using a string literal, as the following
example shows:
example shows.
[tabs]
======
@@ -145,7 +146,7 @@ Java::
Expression exp = parser.parseExpression("new String('hello world').toUpperCase()"); // <1>
String message = exp.getValue(String.class);
----
<1> Construct a new `String` from the literal and make it be upper case.
<1> Construct a new `String` from the literal and convert it to upper case.
Kotlin::
+
@@ -155,10 +156,9 @@ Kotlin::
val exp = parser.parseExpression("new String('hello world').toUpperCase()") // <1>
val message = exp.getValue(String::class.java)
----
<1> Construct a new `String` from the literal and make it be upper case.
<1> Construct a new `String` from the literal and convert it to upper case.
======
Note the use of the generic method: `public <T> T getValue(Class<T> desiredResultType)`.
Using this method removes the need to cast the value of the expression to the desired
result type. An `EvaluationException` is thrown if the value cannot be cast to the
@@ -166,8 +166,8 @@ type `T` or converted by using the registered type converter.
The more common usage of SpEL is to provide an expression string that is evaluated
against a specific object instance (called the root object). The following example shows
how to retrieve the `name` property from an instance of the `Inventor` class or
create a boolean condition:
how to retrieve the `name` property from an instance of the `Inventor` class and how to
reference the `name` property in a boolean expression.
[tabs]
======
@@ -240,7 +240,7 @@ It excludes Java type references, constructors, and bean references. It also req
you to explicitly choose the level of support for properties and methods in expressions.
By default, the `create()` static factory method enables only read access to properties.
You can also obtain a builder to configure the exact level of support needed, targeting
one or some combination of the following:
one or some combination of the following.
* Custom `PropertyAccessor` only (no reflection)
* Data binding properties for read-only access
@@ -252,16 +252,15 @@ one or some combination of the following:
By default, SpEL uses the conversion service available in Spring core
(`org.springframework.core.convert.ConversionService`). This conversion service comes
with many built-in converters for common conversions but is also fully extensible so that
you can add custom conversions between types. Additionally, it is
generics-aware. This means that, when you work with generic types in
expressions, SpEL attempts conversions to maintain type correctness for any objects
it encounters.
with many built-in converters for common conversions, but is also fully extensible so
that you can add custom conversions between types. Additionally, it is generics-aware.
This means that, when you work with generic types in expressions, SpEL attempts
conversions to maintain type correctness for any objects it encounters.
What does this mean in practice? Suppose assignment, using `setValue()`, is being used
to set a `List` property. The type of the property is actually `List<Boolean>`. SpEL
recognizes that the elements of the list need to be converted to `Boolean` before
being placed in it. The following example shows how to do so:
being placed in it. The following example shows how to do so.
[tabs]
======
@@ -325,7 +324,7 @@ constructor before setting the specified value. If the element type does not hav
default constructor, `null` will be added to the array or list. If there is no built-in
or custom converter that knows how to set the value, `null` will remain in the array or
list at the specified index. The following example demonstrates how to automatically grow
the list:
the list.
[tabs]
======
@@ -380,16 +379,25 @@ Kotlin::
----
======
By default, a SpEL expression cannot contain more than 10,000 characters; however, the
`maxExpressionLength` is configurable. If you create a `SpelExpressionParser`
programmatically, you can specify a custom `maxExpressionLength` when creating the
`SpelParserConfiguration` that you provide to the `SpelExpressionParser`. If you wish to
set the `maxExpressionLength` used for parsing SpEL expressions within an
`ApplicationContext` -- for example, in XML bean definitions, `@Value`, etc. -- you can
set a JVM system property or Spring property named `spring.context.expression.maxLength`
to the maximum expression length needed by your application (see
xref:appendix.adoc#appendix-spring-properties[Supported Spring Properties]).
[[expressions-spel-compilation]]
== SpEL Compilation
Spring Framework 4.1 includes a basic expression compiler. Expressions are usually
interpreted, which provides a lot of dynamic flexibility during evaluation but
does not provide optimum performance. For occasional expression usage,
this is fine, but, when used by other components such as Spring Integration,
performance can be very important, and there is no real need for the dynamism.
Spring provides a basic compiler for SpEL expressions. Expressions are usually
interpreted, which provides a lot of dynamic flexibility during evaluation but does not
provide optimum performance. For occasional expression usage, this is fine, but, when
used by other components such as Spring Integration, performance can be very important,
and there is no real need for the dynamism.
The SpEL compiler is intended to address this need. During evaluation, the compiler
generates a Java class that embodies the expression behavior at runtime and uses that
@@ -402,16 +410,17 @@ information can cause trouble later if the types of the various expression eleme
change over time. For this reason, compilation is best suited to expressions whose
type information is not going to change on repeated evaluations.
Consider the following basic expression:
Consider the following basic expression.
[source,java,indent=0,subs="verbatim,quotes"]
----
someArray[0].someProperty.someOtherProperty < 0.1
someArray[0].someProperty.someOtherProperty < 0.1
----
Because the preceding expression involves array access, some property de-referencing,
and numeric operations, the performance gain can be very noticeable. In an example
micro benchmark run of 50000 iterations, it took 75ms to evaluate by using the
interpreter and only 3ms using the compiled version of the expression.
Because the preceding expression involves array access, some property de-referencing, and
numeric operations, the performance gain can be very noticeable. In an example micro
benchmark run of 50,000 iterations, it took 75ms to evaluate by using the interpreter and
only 3ms using the compiled version of the expression.
[[expressions-compiler-configuration]]
@@ -419,33 +428,34 @@ interpreter and only 3ms using the compiled version of the expression.
The compiler is not turned on by default, but you can turn it on in either of two
different ways. You can turn it on by using the parser configuration process
(xref:core/expressions/evaluation.adoc#expressions-parser-configuration[discussed earlier]) or by using a Spring property
when SpEL usage is embedded inside another component. This section discusses both of
these options.
(xref:core/expressions/evaluation.adoc#expressions-parser-configuration[discussed
earlier]) or by using a Spring property when SpEL usage is embedded inside another
component. This section discusses both of these options.
The compiler can operate in one of three modes, which are captured in the
`org.springframework.expression.spel.SpelCompilerMode` enum. The modes are as follows:
`org.springframework.expression.spel.SpelCompilerMode` enum. The modes are as follows.
* `OFF` (default): The compiler is switched off.
* `IMMEDIATE`: In immediate mode, the expressions are compiled as soon as possible. This
is typically after the first interpreted evaluation. If the compiled expression fails
(typically due to a type changing, as described earlier), the caller of the expression
evaluation receives an exception.
* `MIXED`: In mixed mode, the expressions silently switch between interpreted and compiled
mode over time. After some number of interpreted runs, they switch to compiled
form and, if something goes wrong with the compiled form (such as a type changing, as
described earlier), the expression automatically switches back to interpreted form
again. Sometime later, it may generate another compiled form and switch to it. Basically,
the exception that the user gets in `IMMEDIATE` mode is instead handled internally.
is typically after the first interpreted evaluation. If the compiled expression fails
(typically due to a type changing, as described earlier), the caller of the expression
evaluation receives an exception.
* `MIXED`: In mixed mode, the expressions silently switch between interpreted and
compiled mode over time. After some number of interpreted runs, they switch to compiled
form and, if something goes wrong with the compiled form (such as a type changing, as
described earlier), the expression automatically switches back to interpreted form
again. Sometime later, it may generate another compiled form and switch to it.
Basically, the exception that the user gets in `IMMEDIATE` mode is instead handled
internally.
`IMMEDIATE` mode exists because `MIXED` mode could cause issues for expressions that
have side effects. If a compiled expression blows up after partially succeeding, it
may have already done something that has affected the state of the system. If this
has happened, the caller may not want it to silently re-run in interpreted mode,
since part of the expression may be running twice.
since part of the expression may be run twice.
After selecting a mode, use the `SpelParserConfiguration` to configure the parser. The
following example shows how to do so:
following example shows how to do so.
[tabs]
======
@@ -482,15 +492,16 @@ Kotlin::
----
======
When you specify the compiler mode, you can also specify a classloader (passing null is allowed).
Compiled expressions are defined in a child classloader created under any that is supplied.
It is important to ensure that, if a classloader is specified, it can see all the types involved in
the expression evaluation process. If you do not specify a classloader, a default classloader is used
(typically the context classloader for the thread that is running during expression evaluation).
When you specify the compiler mode, you can also specify a `ClassLoader` (passing `null`
is allowed). Compiled expressions are defined in a child `ClassLoader` created under any
that is supplied. It is important to ensure that, if a `ClassLoader` is specified, it can
see all the types involved in the expression evaluation process. If you do not specify a
`ClassLoader`, a default `ClassLoader` is used (typically the context `ClassLoader` for
the thread that is running during expression evaluation).
The second way to configure the compiler is for use when SpEL is embedded inside some
other component and it may not be possible to configure it through a configuration
object. In these cases, it is possible to set the `spring.expression.compiler.mode`
object. In such cases, it is possible to set the `spring.expression.compiler.mode`
property via a JVM system property (or via the
xref:appendix.adoc#appendix-spring-properties[`SpringProperties`] mechanism) to one of the
`SpelCompilerMode` enum values (`off`, `immediate`, or `mixed`).
@@ -499,18 +510,16 @@ xref:appendix.adoc#appendix-spring-properties[`SpringProperties`] mechanism) to
[[expressions-compiler-limitations]]
=== Compiler Limitations
Since Spring Framework 4.1, the basic compilation framework is in place. However, the framework
does not yet support compiling every kind of expression. The initial focus has been on the
common expressions that are likely to be used in performance-critical contexts. The following
kinds of expression cannot be compiled at the moment:
Spring does not support compiling every kind of expression. The primary focus is on
common expressions that are likely to be used in performance-critical contexts. The
following kinds of expressions cannot be compiled.
* Expressions involving assignment
* Expressions relying on the conversion service
* Expressions using custom resolvers or accessors
* Expressions using overloaded operators
* Expressions using array construction syntax
* Expressions using selection or projection
More types of expressions will be compilable in the future.
Compilation of additional kinds of expressions may be supported in the future.
@@ -3,9 +3,11 @@
This section lists the classes used in the examples throughout this chapter.
== `Inventor`
[tabs]
======
Inventor.Java::
Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary",chomp="-packages"]
----
@@ -80,7 +82,7 @@ Inventor.Java::
}
----
Inventor.kt::
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary",chomp="-packages"]
----
@@ -95,9 +97,11 @@ Inventor.kt::
----
======
== `PlaceOfBirth`
[tabs]
======
PlaceOfBirth.java::
Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary",chomp="-packages"]
----
@@ -135,7 +139,7 @@ PlaceOfBirth.java::
}
----
PlaceOfBirth.kt::
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary",chomp="-packages"]
----
@@ -145,9 +149,11 @@ PlaceOfBirth.kt::
----
======
== `Society`
[tabs]
======
Society.java::
Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary",chomp="-packages"]
----
@@ -192,7 +198,7 @@ Society.java::
}
----
Society.kt::
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary",chomp="-packages"]
----
@@ -2,24 +2,4 @@
= Language Reference
:page-section-summary-toc: 1
This section describes how the Spring Expression Language works. It covers the following
topics:
* xref:core/expressions/language-ref/literal.adoc[Literal Expressions]
* xref:core/expressions/language-ref/properties-arrays.adoc[Properties, Arrays, Lists, Maps, and Indexers]
* xref:core/expressions/language-ref/inline-lists.adoc[Inline Lists]
* xref:core/expressions/language-ref/inline-maps.adoc[Inline Maps]
* xref:core/expressions/language-ref/array-construction.adoc[Array Construction]
* xref:core/expressions/language-ref/methods.adoc[Methods]
* xref:core/expressions/language-ref/operators.adoc[Operators]
* xref:core/expressions/language-ref/types.adoc[Types]
* xref:core/expressions/language-ref/constructors.adoc[Constructors]
* xref:core/expressions/language-ref/variables.adoc[Variables]
* xref:core/expressions/language-ref/functions.adoc[User-Defined Functions]
* xref:core/expressions/language-ref/bean-references.adoc[Bean References]
* xref:core/expressions/language-ref/operator-ternary.adoc[Ternary Operator (If-Then-Else)]
* xref:core/expressions/language-ref/operator-elvis.adoc[The Elvis Operator]
* xref:core/expressions/language-ref/operator-safe-navigation.adoc[Safe Navigation Operator]
This section describes how the Spring Expression Language works.
@@ -13,7 +13,7 @@ Java::
int[] numbers1 = (int[]) parser.parseExpression("new int[4]").getValue(context);
// Array with initializer
int[] numbers2 = (int[]) parser.parseExpression("new int[]{1,2,3}").getValue(context);
int[] numbers2 = (int[]) parser.parseExpression("new int[] {1, 2, 3}").getValue(context);
// Multi dimensional array
int[][] numbers3 = (int[][]) parser.parseExpression("new int[4][5]").getValue(context);
@@ -26,14 +26,22 @@ Kotlin::
val numbers1 = parser.parseExpression("new int[4]").getValue(context) as IntArray
// Array with initializer
val numbers2 = parser.parseExpression("new int[]{1,2,3}").getValue(context) as IntArray
val numbers2 = parser.parseExpression("new int[] {1, 2, 3}").getValue(context) as IntArray
// Multi dimensional array
val numbers3 = parser.parseExpression("new int[4][5]").getValue(context) as Array<IntArray>
----
======
[NOTE]
====
You cannot currently supply an initializer when you construct a multi-dimensional array.
====
[CAUTION]
====
Any expression that constructs an array for example, via `new int[4]` or
`new int[] {1, 2, 3}` cannot be compiled. See
xref:core/expressions/evaluation.adoc#expressions-compiler-limitations[Compiler Limitations]
for details.
====
@@ -4,7 +4,7 @@
Projection lets a collection drive the evaluation of a sub-expression, and the result is
a new collection. The syntax for projection is `.![projectionExpression]`. For example,
suppose we have a list of inventors but want the list of cities where they were born.
Effectively, we want to evaluate 'placeOfBirth.city' for every entry in the inventor
Effectively, we want to evaluate `placeOfBirth.city` for every entry in the inventor
list. The following example uses projection to do so:
[tabs]
@@ -13,16 +13,18 @@ Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
// returns ['Smiljan', 'Idvor' ]
List placesOfBirth = (List)parser.parseExpression("members.![placeOfBirth.city]");
// evaluates to ["Smiljan", "Idvor"]
List placesOfBirth = parser.parseExpression("members.![placeOfBirth.city]")
.getValue(societyContext, List.class);
----
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
----
// returns ['Smiljan', 'Idvor' ]
val placesOfBirth = parser.parseExpression("members.![placeOfBirth.city]") as List<*>
// evaluates to ["Smiljan", "Idvor"]
val placesOfBirth = parser.parseExpression("members.![placeOfBirth.city]")
.getValue(societyContext) as List<*>
----
======
@@ -32,5 +34,12 @@ evaluated against each entry in the map (represented as a Java `Map.Entry`). The
of a projection across a map is a list that consists of the evaluation of the projection
expression against each map entry.
[NOTE]
====
The Spring Expression Language also supports safe navigation for collection projection.
See
xref:core/expressions/language-ref/operator-safe-navigation.adoc#expressions-operator-safe-navigation-selection-and-projection[Safe Collection Selection and Projection]
for details.
====
@@ -28,13 +28,14 @@ Kotlin::
======
Selection is supported for arrays and anything that implements `java.lang.Iterable` or
`java.util.Map`. For a list or array, the selection criteria is evaluated against each
individual element. Against a map, the selection criteria is evaluated against each map
entry (objects of the Java type `Map.Entry`). Each map entry has its `key` and `value`
accessible as properties for use in the selection.
`java.util.Map`. For an array or `Iterable`, the selection expression is evaluated
against each individual element. Against a map, the selection expression is evaluated
against each map entry (objects of the Java type `Map.Entry`). Each map entry has its
`key` and `value` accessible as properties for use in the selection.
The following expression returns a new map that consists of those elements of the
original map where the entry's value is less than 27:
Given a `Map` stored in a variable named `#map`, the following expression returns a new
map that consists of those elements of the original map where the entry's value is less
than 27:
[tabs]
======
@@ -42,21 +43,28 @@ Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
Map newMap = parser.parseExpression("map.?[value<27]").getValue();
Map newMap = parser.parseExpression("#map.?[value < 27]").getValue(Map.class);
----
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
----
val newMap = parser.parseExpression("map.?[value<27]").getValue()
val newMap = parser.parseExpression("#map.?[value < 27]").getValue() as Map
----
======
In addition to returning all the selected elements, you can retrieve only the first or
the last element. To obtain the first element matching the selection, the syntax is
`.^[selectionExpression]`. To obtain the last matching selection, the syntax is
`.$[selectionExpression]`.
the last element. To obtain the first element matching the selection expression, the
syntax is `.^[selectionExpression]`. To obtain the last element matching the selection
expression, the syntax is `.$[selectionExpression]`.
[NOTE]
====
The Spring Expression Language also supports safe navigation for collection selection.
See
xref:core/expressions/language-ref/operator-safe-navigation.adoc#expressions-operator-safe-navigation-selection-and-projection[Safe Collection Selection and Projection]
for details.
====
@@ -1,10 +1,26 @@
[[expressions-ref-functions]]
= Functions
You can extend SpEL by registering user-defined functions that can be called within the
expression string. The function is registered through the `EvaluationContext`. The
following example shows how to register a user-defined function to be invoked via reflection
(i.e. a `Method`):
You can extend SpEL by registering user-defined functions that can be called within
expressions by using the `#functionName(...)` syntax. Functions can be registered as
variables in `EvaluationContext` implementations via the `setVariable()` method.
[TIP]
====
`StandardEvaluationContext` also defines `registerFunction(...)` methods that provide a
convenient way to register a function as a `java.lang.reflect.Method` or a
`java.lang.invoke.MethodHandle`.
====
[WARNING]
====
Since functions share a common namespace with
xref:core/expressions/language-ref/variables.adoc[variables] in the evaluation context,
care must be taken to ensure that function names and variable names do not overlap.
====
The following example shows how to register a user-defined function to be invoked via
reflection using a `java.lang.reflect.Method`:
[tabs]
======
@@ -40,11 +56,7 @@ Java::
public abstract class StringUtils {
public static String reverseString(String input) {
StringBuilder backwards = new StringBuilder(input.length());
for (int i = 0; i < input.length(); i++) {
backwards.append(input.charAt(input.length() - 1 - i));
}
return backwards.toString();
return new StringBuilder(input).reverse().toString();
}
}
----
@@ -54,16 +66,12 @@ Kotlin::
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
----
fun reverseString(input: String): String {
val backwards = StringBuilder(input.length)
for (i in 0 until input.length) {
backwards.append(input[input.length - 1 - i])
}
return backwards.toString()
return StringBuilder(input).reverse().toString()
}
----
======
You can then register and use the preceding method, as the following example shows:
You can register and use the preceding method, as the following example shows:
[tabs]
======
@@ -75,8 +83,9 @@ Java::
EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();
context.setVariable("reverseString",
StringUtils.class.getDeclaredMethod("reverseString", String.class));
StringUtils.class.getMethod("reverseString", String.class));
// evaluates to "olleh"
String helloWorldReversed = parser.parseExpression(
"#reverseString('hello')").getValue(context, String.class);
----
@@ -88,16 +97,18 @@ Kotlin::
val parser = SpelExpressionParser()
val context = SimpleEvaluationContext.forReadOnlyDataBinding().build()
context.setVariable("reverseString", ::reverseString::javaMethod)
context.setVariable("reverseString", ::reverseString.javaMethod)
// evaluates to "olleh"
val helloWorldReversed = parser.parseExpression(
"#reverseString('hello')").getValue(context, String::class.java)
----
======
The use of `MethodHandle` is also supported. This enables potentially more efficient use
cases if the `MethodHandle` target and parameters have been fully bound prior to
registration, but partially bound handles are also supported.
A function can also be registered as a `java.lang.invoke.MethodHandle`. This enables
potentially more efficient use cases if the `MethodHandle` target and parameters have
been fully bound prior to registration; however, partially bound handles are also
supported.
Consider the `String#formatted(String, Object...)` instance method, which produces a
message according to a template and a variable number of arguments.
@@ -118,9 +129,9 @@ Java::
MethodType.methodType(String.class, Object[].class));
context.setVariable("message", mh);
// evaluates to "Simple message: <Hello World>"
String message = parser.parseExpression("#message('Simple message: <%s>', 'Hello World', 'ignored')")
.getValue(context, String.class);
//returns "Simple message: <Hello World>"
----
Kotlin::
@@ -134,6 +145,7 @@ Kotlin::
MethodType.methodType(String::class.java, Array<Any>::class.java))
context.setVariable("message", mh)
// evaluates to "Simple message: <Hello World>"
val message = parser.parseExpression("#message('Simple message: <%s>', 'Hello World', 'ignored')")
.getValue(context, String::class.java)
----
@@ -161,9 +173,9 @@ Java::
.bindTo(varargs); //here we have to provide arguments in a single array binding
context.setVariable("message", mh);
// evaluates to "This is a prerecorded message with 3 words: <Oh Hello World!>"
String message = parser.parseExpression("#message()")
.getValue(context, String.class);
//returns "This is a prerecorded message with 3 words: <Oh Hello World!>"
----
Kotlin::
@@ -182,6 +194,7 @@ Kotlin::
.bindTo(varargs) //here we have to provide arguments in a single array binding
context.setVariable("message", mh)
// evaluates to "This is a prerecorded message with 3 words: <Oh Hello World!>"
val message = parser.parseExpression("#message()")
.getValue(context, String::class.java)
----
@@ -3,20 +3,46 @@
SpEL supports the following types of literal expressions.
- strings
- numeric values: integer (`int` or `long`), hexadecimal (`int` or `long`), real (`float`
or `double`)
- boolean values: `true` or `false`
- null
String ::
Strings can be delimited by single quotation marks (`'`) or double quotation marks
(`"`). To include a single quotation mark within a string literal enclosed in single
quotation marks, use two adjacent single quotation mark characters. Similarly, to
include a double quotation mark within a string literal enclosed in double quotation
marks, use two adjacent double quotation mark characters.
Number ::
Numbers support the use of the negative sign, exponential notation, and decimal points.
* Integer: `int` or `long`
* Hexadecimal: `int` or `long`
* Real: `float` or `double`
** By default, real numbers are parsed using `Double.parseDouble()`.
Boolean ::
`true` or `false`
Null ::
`null`
Strings can delimited by single quotation marks (`'`) or double quotation marks (`"`). To
include a single quotation mark within a string literal enclosed in single quotation
marks, use two adjacent single quotation mark characters. Similarly, to include a double
quotation mark within a string literal enclosed in double quotation marks, use two
adjacent double quotation mark characters.
[NOTE]
====
Due to the design and implementation of the Spring Expression Language, literal numbers
are always stored internally as positive numbers.
Numbers support the use of the negative sign, exponential notation, and decimal points.
By default, real numbers are parsed by using `Double.parseDouble()`.
For example, `-2` is stored internally as a positive `2` which is then negated while
evaluating the expression (by calculating the value of `0 - 2`).
This means that it is not possible to represent a negative literal number equal to the
minimum value of that type of number in Java. For example, the minimum supported value
for an `int` in Java is `Integer.MIN_VALUE` which has a value of `-2147483648`. However,
if you include `-2147483648` in a SpEL expression, an exception will be thrown informing
you that the value `2147483648` cannot be parsed as an `int` (because it exceeds the
value of `Integer.MAX_VALUE` which is `2147483647`).
If you need to use the minimum value for a particular type of number within a SpEL
expression, you can either reference the `MIN_VALUE` constant for the respective wrapper
type (such as `Integer.MIN_VALUE`, `Long.MIN_VALUE`, etc.) or calculate the minimum
value. For example, to use the minimum integer value:
- `T(Integer).MIN_VALUE` -- requires a `StandardEvaluationContext`
- `-2^31` -- can be used with any type of `EvaluationContext`
====
The following listing shows simple usage of literals. Typically, they are not used in
isolation like this but, rather, as part of a more complex expression -- for example,
@@ -1,12 +1,27 @@
[[expressions-operator-safe-navigation]]
= Safe Navigation Operator
The safe navigation operator is used to avoid a `NullPointerException` and comes from
the https://www.groovy-lang.org/operators.html#_safe_navigation_operator[Groovy]
language. Typically, when you have a reference to an object, you might need to verify that
it is not null before accessing methods or properties of the object. To avoid this, the
safe navigation operator returns null instead of throwing an exception. The following
example shows how to use the safe navigation operator:
The safe navigation operator (`?`) is used to avoid a `NullPointerException` and comes
from the https://www.groovy-lang.org/operators.html#_safe_navigation_operator[Groovy]
language. Typically, when you have a reference to an object, you might need to verify
that it is not `null` before accessing methods or properties of the object. To avoid
this, the safe navigation operator returns `null` for the particular null-safe operation
instead of throwing an exception.
[WARNING]
====
When the safe navigation operator evaluates to `null` for a particular null-safe
operation within a compound expression, the remainder of the compound expression will
still be evaluated.
See <<expressions-operator-safe-navigation-compound-expressions>> for details.
====
[[expressions-operator-safe-navigation-property-access]]
== Safe Property and Method Access
The following example shows how to use the safe navigation operator for property access
(`?.`).
[tabs]
======
@@ -20,13 +35,18 @@ Java::
Inventor tesla = new Inventor("Nikola Tesla", "Serbian");
tesla.setPlaceOfBirth(new PlaceOfBirth("Smiljan"));
String city = parser.parseExpression("placeOfBirth?.city").getValue(context, tesla, String.class);
System.out.println(city); // Smiljan
// evaluates to "Smiljan"
String city = parser.parseExpression("placeOfBirth?.city") // <1>
.getValue(context, tesla, String.class);
tesla.setPlaceOfBirth(null);
city = parser.parseExpression("placeOfBirth?.city").getValue(context, tesla, String.class);
System.out.println(city); // null - does not throw NullPointerException!!!
// evaluates to null - does not throw NullPointerException
city = parser.parseExpression("placeOfBirth?.city") // <2>
.getValue(context, tesla, String.class);
----
<1> Use safe navigation operator on non-null `placeOfBirth` property
<2> Use safe navigation operator on null `placeOfBirth` property
Kotlin::
+
@@ -38,14 +58,306 @@ Kotlin::
val tesla = Inventor("Nikola Tesla", "Serbian")
tesla.setPlaceOfBirth(PlaceOfBirth("Smiljan"))
var city = parser.parseExpression("placeOfBirth?.city").getValue(context, tesla, String::class.java)
println(city) // Smiljan
// evaluates to "Smiljan"
var city = parser.parseExpression("placeOfBirth?.city") // <1>
.getValue(context, tesla, String::class.java)
tesla.setPlaceOfBirth(null)
city = parser.parseExpression("placeOfBirth?.city").getValue(context, tesla, String::class.java)
println(city) // null - does not throw NullPointerException!!!
// evaluates to null - does not throw NullPointerException
city = parser.parseExpression("placeOfBirth?.city") // <2>
.getValue(context, tesla, String::class.java)
----
<1> Use safe navigation operator on non-null `placeOfBirth` property
<2> Use safe navigation operator on null `placeOfBirth` property
======
[NOTE]
====
The safe navigation operator also applies to method invocations on an object.
For example, the expression `#calculator?.max(4, 2)` evaluates to `null` if the
`#calculator` variable has not been configured in the context. Otherwise, the
`max(int, int)` method will be invoked on the `#calculator`.
====
[[expressions-operator-safe-navigation-selection-and-projection]]
== Safe Collection Selection and Projection
The Spring Expression Language supports safe navigation for
xref:core/expressions/language-ref/collection-selection.adoc[collection selection] and
xref:core/expressions/language-ref/collection-projection.adoc[collection projection] via
the following operators.
* null-safe selection: `?.?`
* null-safe select first: `?.^`
* null-safe select last: `?.$`
* null-safe projection: `?.!`
The following example shows how to use the safe navigation operator for collection
selection (`?.?`).
[tabs]
======
Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
ExpressionParser parser = new SpelExpressionParser();
IEEE society = new IEEE();
StandardEvaluationContext context = new StandardEvaluationContext(society);
String expression = "members?.?[nationality == 'Serbian']"; // <1>
// evaluates to [Inventor("Nikola Tesla")]
List<Inventor> list = (List<Inventor>) parser.parseExpression(expression)
.getValue(context);
society.members = null;
// evaluates to null - does not throw a NullPointerException
list = (List<Inventor>) parser.parseExpression(expression)
.getValue(context);
----
<1> Use null-safe selection operator on potentially null `members` list
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
----
val parser = SpelExpressionParser()
val society = IEEE()
val context = StandardEvaluationContext(society)
val expression = "members?.?[nationality == 'Serbian']" // <1>
// evaluates to [Inventor("Nikola Tesla")]
var list = parser.parseExpression(expression)
.getValue(context) as List<Inventor>
society.members = null
// evaluates to null - does not throw a NullPointerException
list = parser.parseExpression(expression)
.getValue(context) as List<Inventor>
----
<1> Use null-safe selection operator on potentially null `members` list
======
The following example shows how to use the "null-safe select first" operator for
collections (`?.^`).
[tabs]
======
Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
ExpressionParser parser = new SpelExpressionParser();
IEEE society = new IEEE();
StandardEvaluationContext context = new StandardEvaluationContext(society);
String expression =
"members?.^[nationality == 'Serbian' || nationality == 'Idvor']"; // <1>
// evaluates to Inventor("Nikola Tesla")
Inventor inventor = parser.parseExpression(expression)
.getValue(context, Inventor.class);
society.members = null;
// evaluates to null - does not throw a NullPointerException
inventor = parser.parseExpression(expression)
.getValue(context, Inventor.class);
----
<1> Use "null-safe select first" operator on potentially null `members` list
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
----
val parser = SpelExpressionParser()
val society = IEEE()
val context = StandardEvaluationContext(society)
val expression =
"members?.^[nationality == 'Serbian' || nationality == 'Idvor']" // <1>
// evaluates to Inventor("Nikola Tesla")
var inventor = parser.parseExpression(expression)
.getValue(context, Inventor::class.java)
society.members = null
// evaluates to null - does not throw a NullPointerException
inventor = parser.parseExpression(expression)
.getValue(context, Inventor::class.java)
----
<1> Use "null-safe select first" operator on potentially null `members` list
======
The following example shows how to use the "null-safe select last" operator for
collections (`?.$`).
[tabs]
======
Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
ExpressionParser parser = new SpelExpressionParser();
IEEE society = new IEEE();
StandardEvaluationContext context = new StandardEvaluationContext(society);
String expression =
"members?.$[nationality == 'Serbian' || nationality == 'Idvor']"; // <1>
// evaluates to Inventor("Pupin")
Inventor inventor = parser.parseExpression(expression)
.getValue(context, Inventor.class);
society.members = null;
// evaluates to null - does not throw a NullPointerException
inventor = parser.parseExpression(expression)
.getValue(context, Inventor.class);
----
<1> Use "null-safe select last" operator on potentially null `members` list
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
----
val parser = SpelExpressionParser()
val society = IEEE()
val context = StandardEvaluationContext(society)
val expression =
"members?.$[nationality == 'Serbian' || nationality == 'Idvor']" // <1>
// evaluates to Inventor("Pupin")
var inventor = parser.parseExpression(expression)
.getValue(context, Inventor::class.java)
society.members = null
// evaluates to null - does not throw a NullPointerException
inventor = parser.parseExpression(expression)
.getValue(context, Inventor::class.java)
----
<1> Use "null-safe select last" operator on potentially null `members` list
======
The following example shows how to use the safe navigation operator for collection
projection (`?.!`).
[tabs]
======
Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
ExpressionParser parser = new SpelExpressionParser();
IEEE society = new IEEE();
StandardEvaluationContext context = new StandardEvaluationContext(society);
// evaluates to ["Smiljan", "Idvor"]
List placesOfBirth = parser.parseExpression("members?.![placeOfBirth.city]") // <1>
.getValue(context, List.class);
society.members = null;
// evaluates to null - does not throw a NullPointerException
placesOfBirth = parser.parseExpression("members?.![placeOfBirth.city]") // <2>
.getValue(context, List.class);
----
<1> Use null-safe projection operator on non-null `members` list
<2> Use null-safe projection operator on null `members` list
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
----
val parser = SpelExpressionParser()
val society = IEEE()
val context = StandardEvaluationContext(society)
// evaluates to ["Smiljan", "Idvor"]
var placesOfBirth = parser.parseExpression("members?.![placeOfBirth.city]") // <1>
.getValue(context, List::class.java)
society.members = null
// evaluates to null - does not throw a NullPointerException
placesOfBirth = parser.parseExpression("members?.![placeOfBirth.city]") // <2>
.getValue(context, List::class.java)
----
<1> Use null-safe projection operator on non-null `members` list
<2> Use null-safe projection operator on null `members` list
======
[[expressions-operator-safe-navigation-compound-expressions]]
== Null-safe Operations in Compound Expressions
As mentioned at the beginning of this section, when the safe navigation operator
evaluates to `null` for a particular null-safe operation within a compound expression,
the remainder of the compound expression will still be evaluated. This means that the
safe navigation operator must be applied throughout a compound expression in order to
avoid any unwanted `NullPointerException`.
Given the expression `#person?.address.city`, if `#person` is `null` the safe navigation
operator (`?.`) ensures that no exception will be thrown when attempting to access the
`address` property of `#person`. However, since `#person?.address` evaluates to `null`, a
`NullPointerException` will be thrown when attempting to access the `city` property of
`null`. To address that, you can apply null-safe navigation throughout the compound
expression as in `#person?.address?.city`. That expression will safely evaluate to `null`
if either `#person` or `#person?.address` evaluates to `null`.
The following example demonstrates how to use the "null-safe select first" operator
(`?.^`) on a collection combined with null-safe property access (`?.`) within a compound
expression. If `members` is `null`, the result of the "null-safe select first" operator
(`members?.^[nationality == 'Serbian']`) evaluates to `null`, and the additional use of
the safe navigation operator (`?.name`) ensures that the entire compound expression
evaluates to `null` instead of throwing an exception.
[tabs]
======
Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
ExpressionParser parser = new SpelExpressionParser();
IEEE society = new IEEE();
StandardEvaluationContext context = new StandardEvaluationContext(society);
String expression = "members?.^[nationality == 'Serbian']?.name"; // <1>
// evaluates to "Nikola Tesla"
String name = parser.parseExpression(expression)
.getValue(context, String.class);
society.members = null;
// evaluates to null - does not throw a NullPointerException
name = parser.parseExpression(expression)
.getValue(context, String.class);
----
<1> Use "null-safe select first" and null-safe property access operators within compound expression.
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
----
val parser = SpelExpressionParser()
val society = IEEE()
val context = StandardEvaluationContext(society)
val expression = "members?.^[nationality == 'Serbian']?.name" // <1>
// evaluates to "Nikola Tesla"
String name = parser.parseExpression(expression)
.getValue(context, String::class.java)
society.members = null
// evaluates to null - does not throw a NullPointerException
name = parser.parseExpression(expression)
.getValue(context, String::class.java)
----
<1> Use "null-safe select first" and null-safe property access operators within compound expression.
======
@@ -5,8 +5,11 @@ The Spring Expression Language supports the following kinds of operators:
* xref:core/expressions/language-ref/operators.adoc#expressions-operators-relational[Relational Operators]
* xref:core/expressions/language-ref/operators.adoc#expressions-operators-logical[Logical Operators]
* xref:core/expressions/language-ref/operators.adoc#expressions-operators-string[String Operators]
* xref:core/expressions/language-ref/operators.adoc#expressions-operators-mathematical[Mathematical Operators]
* xref:core/expressions/language-ref/operators.adoc#expressions-assignment[The Assignment Operator]
* xref:core/expressions/language-ref/operators.adoc#expressions-operators-overloaded[Overloaded Operators]
[[expressions-operators-relational]]
@@ -15,7 +18,7 @@ The Spring Expression Language supports the following kinds of operators:
The relational operators (equal, not equal, less than, less than or equal, greater than,
and greater than or equal) are supported by using standard operator notation.
These operators work on `Number` types as well as types implementing `Comparable`.
The following listing shows a few examples of operators:
The following listing shows a few examples of relational operators:
[tabs]
======
@@ -65,53 +68,9 @@ If you prefer numeric comparisons instead, avoid number-based `null` comparisons
in favor of comparisons against zero (for example, `X > 0` or `X < 0`).
====
In addition to the standard relational operators, SpEL supports the `instanceof` and regular
expression-based `matches` operator. The following listing shows examples of both:
[tabs]
======
Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
// evaluates to false
boolean falseValue = parser.parseExpression(
"'xyz' instanceof T(Integer)").getValue(Boolean.class);
// evaluates to true
boolean trueValue = parser.parseExpression(
"'5.00' matches '^-?\\d+(\\.\\d{2})?$'").getValue(Boolean.class);
// evaluates to false
boolean falseValue = parser.parseExpression(
"'5.0067' matches '^-?\\d+(\\.\\d{2})?$'").getValue(Boolean.class);
----
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
----
// evaluates to false
val falseValue = parser.parseExpression(
"'xyz' instanceof T(Integer)").getValue(Boolean::class.java)
// evaluates to true
val trueValue = parser.parseExpression(
"'5.00' matches '^-?\\d+(\\.\\d{2})?$'").getValue(Boolean::class.java)
// evaluates to false
val falseValue = parser.parseExpression(
"'5.0067' matches '^-?\\d+(\\.\\d{2})?$'").getValue(Boolean::class.java)
----
======
CAUTION: Be careful with primitive types, as they are immediately boxed up to their
wrapper types. For example, `1 instanceof T(int)` evaluates to `false`, while
`1 instanceof T(Integer)` evaluates to `true`, as expected.
Each symbolic operator can also be specified as a purely alphabetic equivalent. This
avoids problems where the symbols used have special meaning for the document type in
which the expression is embedded (such as in an XML document). The textual equivalents are:
Each symbolic operator can also be specified as a purely textual equivalent. This avoids
problems where the symbols used have special meaning for the document type in which the
expression is embedded (such as in an XML document). The textual equivalents are:
* `lt` (`<`)
* `gt` (`>`)
@@ -119,22 +78,117 @@ which the expression is embedded (such as in an XML document). The textual equiv
* `ge` (`>=`)
* `eq` (`==`)
* `ne` (`!=`)
* `div` (`/`)
* `mod` (`%`)
* `not` (`!`).
All of the textual operators are case-insensitive.
In addition to the standard relational operators, SpEL supports the `between`,
`instanceof`, and regular expression-based `matches` operators. The following listing
shows examples of all three:
[tabs]
======
Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
boolean result;
// evaluates to true
result = parser.parseExpression(
"1 between {1, 5}").getValue(Boolean.class);
// evaluates to false
result = parser.parseExpression(
"1 between {10, 15}").getValue(Boolean.class);
// evaluates to true
result = parser.parseExpression(
"'elephant' between {'aardvark', 'zebra'}").getValue(Boolean.class);
// evaluates to false
result = parser.parseExpression(
"'elephant' between {'aardvark', 'cobra'}").getValue(Boolean.class);
// evaluates to true
result = parser.parseExpression(
"123 instanceof T(Integer)").getValue(Boolean.class);
// evaluates to false
result = parser.parseExpression(
"'xyz' instanceof T(Integer)").getValue(Boolean.class);
// evaluates to true
result = parser.parseExpression(
"'5.00' matches '^-?\\d+(\\.\\d{2})?$'").getValue(Boolean.class);
// evaluates to false
result = parser.parseExpression(
"'5.0067' matches '^-?\\d+(\\.\\d{2})?$'").getValue(Boolean.class);
----
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
----
// evaluates to true
var result = parser.parseExpression(
"1 between {1, 5}").getValue(Boolean::class.java)
// evaluates to false
result = parser.parseExpression(
"1 between {10, 15}").getValue(Boolean::class.java)
// evaluates to true
result = parser.parseExpression(
"'elephant' between {'aardvark', 'zebra'}").getValue(Boolean::class.java)
// evaluates to false
result = parser.parseExpression(
"'elephant' between {'aardvark', 'cobra'}").getValue(Boolean::class.java)
// evaluates to true
result = parser.parseExpression(
"123 instanceof T(Integer)").getValue(Boolean::class.java)
// evaluates to false
result = parser.parseExpression(
"'xyz' instanceof T(Integer)").getValue(Boolean::class.java)
// evaluates to true
result = parser.parseExpression(
"'5.00' matches '^-?\\d+(\\.\\d{2})?$'").getValue(Boolean::class.java)
// evaluates to false
result = parser.parseExpression(
"'5.0067' matches '^-?\\d+(\\.\\d{2})?$'").getValue(Boolean::class.java)
----
======
[CAUTION]
====
The syntax for the `between` operator is `<input> between {<range_begin>, <range_end>}`,
which is effectively a shortcut for `<input> >= <range_begin> && <input> \<= <range_end>}`.
Consequently, `1 between {1, 5}` evaluates to `true`, while `1 between {5, 1}` evaluates
to `false`.
====
CAUTION: Be careful with primitive types, as they are immediately boxed up to their
wrapper types. For example, `1 instanceof T(int)` evaluates to `false`, while
`1 instanceof T(Integer)` evaluates to `true`.
[[expressions-operators-logical]]
== Logical Operators
SpEL supports the following logical operators:
SpEL supports the following logical (`boolean`) operators:
* `and` (`&&`)
* `or` (`||`)
* `not` (`!`)
All of the textual operators are case-insensitive.
The following example shows how to use the logical operators:
[tabs]
@@ -167,6 +221,7 @@ Java::
boolean falseValue = parser.parseExpression("!true").getValue(Boolean.class);
// -- AND and NOT --
String expression = "isMember('Nikola Tesla') and !isMember('Mihajlo Pupin')";
boolean falseValue = parser.parseExpression(expression).getValue(societyContext, Boolean.class);
----
@@ -199,20 +254,24 @@ Kotlin::
val falseValue = parser.parseExpression("!true").getValue(Boolean::class.java)
// -- AND and NOT --
val expression = "isMember('Nikola Tesla') and !isMember('Mihajlo Pupin')"
val falseValue = parser.parseExpression(expression).getValue(societyContext, Boolean::class.java)
----
======
[[expressions-operators-mathematical]]
== Mathematical Operators
[[expressions-operators-string]]
== String Operators
You can use the addition operator (`+`) on both numbers and strings. You can use the
subtraction (`-`), multiplication (`*`), and division (`/`) operators only on numbers.
You can also use the modulus (`%`) and exponential power (`^`) operators on numbers.
Standard operator precedence is enforced. The following example shows the mathematical
operators in use:
You can use the following operators on strings.
* concatenation (`+`)
* subtraction (`-`)
- for use with a string containing a single character
* repeat (`*`)
The following example shows the `String` operators in use:
[tabs]
======
@@ -220,67 +279,212 @@ Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
// Addition
int two = parser.parseExpression("1 + 1").getValue(Integer.class); // 2
// -- Concatenation --
String testString = parser.parseExpression(
"'test' + ' ' + 'string'").getValue(String.class); // 'test string'
// evaluates to "hello world"
String helloWorld = parser.parseExpression("'hello' + ' ' + 'world'")
.getValue(String.class);
// Subtraction
int four = parser.parseExpression("1 - -3").getValue(Integer.class); // 4
// -- Character Subtraction --
double d = parser.parseExpression("1000.00 - 1e4").getValue(Double.class); // -9000
// evaluates to 'a'
char ch = parser.parseExpression("'d' - 3")
.getValue(char.class);
// Multiplication
int six = parser.parseExpression("-2 * -3").getValue(Integer.class); // 6
// -- Repeat --
double twentyFour = parser.parseExpression("2.0 * 3e0 * 4").getValue(Double.class); // 24.0
// Division
int minusTwo = parser.parseExpression("6 / -3").getValue(Integer.class); // -2
double one = parser.parseExpression("8.0 / 4e0 / 2").getValue(Double.class); // 1.0
// Modulus
int three = parser.parseExpression("7 % 4").getValue(Integer.class); // 3
int one = parser.parseExpression("8 / 5 % 2").getValue(Integer.class); // 1
// Operator precedence
int minusTwentyOne = parser.parseExpression("1+2-3*8").getValue(Integer.class); // -21
// evaluates to "abcabc"
String repeated = parser.parseExpression("'abc' * 2")
.getValue(String.class);
----
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
----
// Addition
val two = parser.parseExpression("1 + 1").getValue(Int::class.java) // 2
// -- Concatenation --
val testString = parser.parseExpression(
"'test' + ' ' + 'string'").getValue(String::class.java) // 'test string'
// evaluates to "hello world"
val helloWorld = parser.parseExpression("'hello' + ' ' + 'world'")
.getValue(String::class.java)
// -- Character Subtraction --
// evaluates to 'a'
val ch = parser.parseExpression("'d' - 3")
.getValue(Character::class.java);
// -- Repeat --
// evaluates to "abcabc"
val repeated = parser.parseExpression("'abc' * 2")
.getValue(String::class.java);
----
======
[[expressions-operators-mathematical]]
== Mathematical Operators
You can use the following operators on numbers, and standard operator precedence is enforced.
* addition (`+`)
* subtraction (`-`)
* increment (`{pp}`)
* decrement (`--`)
* multiplication (`*`)
* division (`/`)
* modulus (`%`)
* exponential power (`^`)
The division and modulus operators can also be specified as a purely textual equivalent.
This avoids problems where the symbols used have special meaning for the document type in
which the expression is embedded (such as in an XML document). The textual equivalents
are:
* `div` (`/`)
* `mod` (`%`)
All of the textual operators are case-insensitive.
[NOTE]
====
The increment and decrement operators can be used with either prefix (`{pp}A`, `--A`) or
postfix (`A{pp}`, `A--`) notation with variables or properties that can be written to.
====
The following example shows the mathematical operators in use:
[tabs]
======
Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
Inventor inventor = new Inventor();
EvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().build();
// -- Addition --
int two = parser.parseExpression("1 + 1").getValue(int.class); // 2
// -- Subtraction --
int four = parser.parseExpression("1 - -3").getValue(int.class); // 4
double d = parser.parseExpression("1000.00 - 1e4").getValue(double.class); // -9000
// -- Increment --
// The counter property in Inventor has an initial value of 0.
// evaluates to 2; counter is now 1
two = parser.parseExpression("counter++ + 2").getValue(context, inventor, int.class);
// evaluates to 5; counter is now 2
int five = parser.parseExpression("3 + ++counter").getValue(context, inventor, int.class);
// -- Decrement --
// The counter property in Inventor has a value of 2.
// evaluates to 6; counter is now 1
int six = parser.parseExpression("counter-- + 4").getValue(context, inventor, int.class);
// evaluates to 5; counter is now 0
five = parser.parseExpression("5 + --counter").getValue(context, inventor, int.class);
// -- Multiplication --
six = parser.parseExpression("-2 * -3").getValue(int.class); // 6
double twentyFour = parser.parseExpression("2.0 * 3e0 * 4").getValue(double.class); // 24.0
// -- Division --
int minusTwo = parser.parseExpression("6 / -3").getValue(int.class); // -2
double one = parser.parseExpression("8.0 / 4e0 / 2").getValue(double.class); // 1.0
// -- Modulus --
int three = parser.parseExpression("7 % 4").getValue(int.class); // 3
int oneInt = parser.parseExpression("8 / 5 % 2").getValue(int.class); // 1
// -- Exponential power --
int maxInt = parser.parseExpression("(2^31) - 1").getValue(int.class); // Integer.MAX_VALUE
int minInt = parser.parseExpression("-2^31").getValue(int.class); // Integer.MIN_VALUE
// -- Operator precedence --
int minusTwentyOne = parser.parseExpression("1+2-3*8").getValue(int.class); // -21
----
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
----
val inventor = Inventor()
val context = SimpleEvaluationContext.forReadWriteDataBinding().build()
// -- Addition --
var two = parser.parseExpression("1 + 1").getValue(Int::class.java) // 2
// -- Subtraction --
// Subtraction
val four = parser.parseExpression("1 - -3").getValue(Int::class.java) // 4
val d = parser.parseExpression("1000.00 - 1e4").getValue(Double::class.java) // -9000
// Multiplication
val six = parser.parseExpression("-2 * -3").getValue(Int::class.java) // 6
// -- Increment --
// The counter property in Inventor has an initial value of 0.
// evaluates to 2; counter is now 1
two = parser.parseExpression("counter++ + 2").getValue(context, inventor, Int::class.java)
// evaluates to 5; counter is now 2
var five = parser.parseExpression("3 + ++counter").getValue(context, inventor, Int::class.java)
// -- Decrement --
// The counter property in Inventor has a value of 2.
// evaluates to 6; counter is now 1
var six = parser.parseExpression("counter-- + 4").getValue(context, inventor, Int::class.java)
// evaluates to 5; counter is now 0
five = parser.parseExpression("5 + --counter").getValue(context, inventor, Int::class.java)
// -- Multiplication --
six = parser.parseExpression("-2 * -3").getValue(Int::class.java) // 6
val twentyFour = parser.parseExpression("2.0 * 3e0 * 4").getValue(Double::class.java) // 24.0
// Division
// -- Division --
val minusTwo = parser.parseExpression("6 / -3").getValue(Int::class.java) // -2
val one = parser.parseExpression("8.0 / 4e0 / 2").getValue(Double::class.java) // 1.0
// Modulus
// -- Modulus --
val three = parser.parseExpression("7 % 4").getValue(Int::class.java) // 3
val one = parser.parseExpression("8 / 5 % 2").getValue(Int::class.java) // 1
val oneInt = parser.parseExpression("8 / 5 % 2").getValue(Int::class.java) // 1
// -- Exponential power --
val maxInt = parser.parseExpression("(2^31) - 1").getValue(Int::class.java) // Integer.MAX_VALUE
val minInt = parser.parseExpression("-2^31").getValue(Int::class.java) // Integer.MIN_VALUE
// -- Operator precedence --
// Operator precedence
val minusTwentyOne = parser.parseExpression("1+2-3*8").getValue(Int::class.java) // -21
----
======
@@ -325,3 +529,83 @@ Kotlin::
======
[[expressions-operators-overloaded]]
== Overloaded Operators
By default, the mathematical operations defined in SpEL's `Operation` enum (`ADD`,
`SUBTRACT`, `DIVIDE`, `MULTIPLY`, `MODULUS`, and `POWER`) support simple types like
numbers. By providing an implementation of `OperatorOverloader`, the expression language
can support these operations on other types.
For example, if we want to overload the `ADD` operator to allow two lists to be
concatenated using the `+` sign, we can implement a custom `OperatorOverloader` as
follows.
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
pubic class ListConcatenation implements OperatorOverloader {
@Override
public boolean overridesOperation(Operation operation, Object left, Object right) {
return (operation == Operation.ADD &&
left instanceof List && right instanceof List);
}
@Override
@SuppressWarnings("unchecked")
public Object operate(Operation operation, Object left, Object right) {
if (operation == Operation.ADD &&
left instanceof List list1 && right instanceof List list2) {
List result = new ArrayList(list1);
result.addAll(list2);
return result;
}
throw new UnsupportedOperationException(
"No overload for operation %s and operands [%s] and [%s]"
.formatted(operation, left, right));
}
}
----
If we register `ListConcatenation` as the `OperatorOverloader` in a
`StandardEvaluationContext`, we can then evaluate expressions like `{1, 2, 3} + {4, 5}`
as demonstrated in the following example.
[tabs]
======
Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
StandardEvaluationContext context = new StandardEvaluationContext();
context.setOperatorOverloader(new ListConcatenation());
// evaluates to a new list: [1, 2, 3, 4, 5]
parser.parseExpression("{1, 2, 3} + {2 + 2, 5}").getValue(context, List.class);
----
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
----
StandardEvaluationContext context = StandardEvaluationContext()
context.setOperatorOverloader(ListConcatenation())
// evaluates to a new list: [1, 2, 3, 4, 5]
parser.parseExpression("{1, 2, 3} + {2 + 2, 5}").getValue(context, List::class.java)
----
======
[NOTE]
====
An `OperatorOverloader` does not change the default semantics for an operator. For
example, `2 + 2` in the above example still evaluates to `4`.
====
[CAUTION]
====
Any expression that uses an overloaded operator cannot be compiled. See
xref:core/expressions/evaluation.adoc#expressions-compiler-limitations[Compiler Limitations]
for details.
====
@@ -1,5 +1,5 @@
[[expressions-templating]]
= Expression templating
= Expression Templating
Expression templates allow mixing literal text with one or more evaluation blocks.
Each evaluation block is delimited with prefix and suffix characters that you can
@@ -32,53 +32,13 @@ Kotlin::
======
The string is evaluated by concatenating the literal text `'random number is '` with the
result of evaluating the expression inside the `#{ }` delimiter (in this case, the result
of calling that `random()` method). The second argument to the `parseExpression()` method
is of the type `ParserContext`. The `ParserContext` interface is used to influence how
the expression is parsed in order to support the expression templating functionality.
The definition of `TemplateParserContext` follows:
[tabs]
======
Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
public class TemplateParserContext implements ParserContext {
public String getExpressionPrefix() {
return "#{";
}
public String getExpressionSuffix() {
return "}";
}
public boolean isTemplate() {
return true;
}
}
----
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
----
class TemplateParserContext : ParserContext {
override fun getExpressionPrefix(): String {
return "#{"
}
override fun getExpressionSuffix(): String {
return "}"
}
override fun isTemplate(): Boolean {
return true
}
}
----
======
result of evaluating the expression inside the `#{ }` delimiters (in this case, the
result of calling that `random()` method). The second argument to the `parseExpression()`
method is of the type `ParserContext`. The `ParserContext` interface is used to influence
how the expression is parsed in order to support the expression templating functionality.
The `TemplateParserContext` used in the previous example resides in the
`org.springframework.expression.common` package and is an implementation of the
`ParserContext` which by default configures the prefix and suffix to `#{` and `}`,
respectively.
@@ -1,20 +1,41 @@
[[expressions-ref-variables]]
= Variables
You can reference variables in the expression by using the `#variableName` syntax. Variables
are set by using the `setVariable` method on `EvaluationContext` implementations.
You can reference variables in an expression by using the `#variableName` syntax. Variables
are set by using the `setVariable()` method in `EvaluationContext` implementations.
[NOTE]
====
Valid variable names must be composed of one or more of the following supported
Variable names must be begin with a letter (as defined below), an underscore, or a dollar
sign.
Variable names must be composed of one or more of the following supported types of
characters.
* letters: `A` to `Z` and `a` to `z`
* digits: `0` to `9`
* letter: any character for which `java.lang.Character.isLetter(char)` returns `true`
- This includes letters such as `A` to `Z`, `a` to `z`, `ü`, `ñ`, and `é` as well as
letters from other character sets such as Chinese, Japanese, Cyrillic, etc.
* digit: `0` to `9`
* underscore: `_`
* dollar sign: `$`
====
[TIP]
====
When setting a variable or root context object in the `EvaluationContext`, it is advised
that the type of the variable or root context object be `public`.
Otherwise, certain types of SpEL expressions involving a variable or root context object
with a non-public type may fail to evaluate or compile.
====
[WARNING]
====
Since variables share a common namespace with
xref:core/expressions/language-ref/functions.adoc[functions] in the evaluation context,
care must be taken to ensure that variable names and functions names do not overlap.
====
The following example shows how to use variables.
[tabs]
@@ -29,7 +50,7 @@ Java::
context.setVariable("newName", "Mike Tesla");
parser.parseExpression("name = #newName").getValue(context, tesla);
System.out.println(tesla.getName()) // "Mike Tesla"
System.out.println(tesla.getName()); // "Mike Tesla"
----
Kotlin::
@@ -53,8 +74,10 @@ Kotlin::
The `#this` variable is always defined and refers to the current evaluation object
(against which unqualified references are resolved). The `#root` variable is always
defined and refers to the root context object. Although `#this` may vary as components of
an expression are evaluated, `#root` always refers to the root. The following examples
show how to use the `#this` and `#root` variables:
an expression are evaluated, `#root` always refers to the root.
The following example shows how to use the `#this` variable in conjunction with
xref:core/expressions/language-ref/collection-selection.adoc[collection selection].
[tabs]
======
@@ -62,40 +85,95 @@ Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
// create an array of integers
List<Integer> primes = new ArrayList<>();
primes.addAll(Arrays.asList(2,3,5,7,11,13,17));
// Create a list of prime integers.
List<Integer> primes = List.of(2, 3, 5, 7, 11, 13, 17);
// create parser and set variable 'primes' as the array of integers
// Create parser and set variable 'primes' as the list of integers.
ExpressionParser parser = new SpelExpressionParser();
EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataAccess();
EvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().build();
context.setVariable("primes", primes);
// all prime numbers > 10 from the list (using selection ?{...})
// evaluates to [11, 13, 17]
List<Integer> primesGreaterThanTen = (List<Integer>) parser.parseExpression(
"#primes.?[#this>10]").getValue(context);
// Select all prime numbers > 10 from the list (using selection ?{...}).
String expression = "#primes.?[#this > 10]";
// Evaluates to a list containing [11, 13, 17].
List<Integer> primesGreaterThanTen =
parser.parseExpression(expression).getValue(context, List.class);
----
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
----
// create an array of integers
val primes = ArrayList<Int>()
primes.addAll(listOf(2, 3, 5, 7, 11, 13, 17))
// Create a list of prime integers.
val primes = listOf(2, 3, 5, 7, 11, 13, 17)
// create parser and set variable 'primes' as the array of integers
// Create parser and set variable 'primes' as the list of integers.
val parser = SpelExpressionParser()
val context = SimpleEvaluationContext.forReadOnlyDataAccess()
val context = SimpleEvaluationContext.forReadWriteDataBinding().build()
context.setVariable("primes", primes)
// all prime numbers > 10 from the list (using selection ?{...})
// evaluates to [11, 13, 17]
val primesGreaterThanTen = parser.parseExpression(
"#primes.?[#this>10]").getValue(context) as List<Int>
// Select all prime numbers > 10 from the list (using selection ?{...}).
val expression = "#primes.?[#this > 10]"
// Evaluates to a list containing [11, 13, 17].
val primesGreaterThanTen = parser.parseExpression(expression)
.getValue(context) as List<Int>
----
======
The following example shows how to use the `#this` and `#root` variables together in
conjunction with
xref:core/expressions/language-ref/collection-projection.adoc[collection projection].
[tabs]
======
Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
// Create parser and evaluation context.
ExpressionParser parser = new SpelExpressionParser();
EvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().build();
// Create an inventor to use as the root context object.
Inventor tesla = new Inventor("Nikola Tesla");
tesla.setInventions("Telephone repeater", "Tesla coil transformer");
// Iterate over all inventions of the Inventor referenced as the #root
// object, and generate a list of strings whose contents take the form
// "<inventor's name> invented the <invention>." (using projection !{...}).
String expression = "#root.inventions.![#root.name + ' invented the ' + #this + '.']";
// Evaluates to a list containing:
// "Nikola Tesla invented the Telephone repeater."
// "Nikola Tesla invented the Tesla coil transformer."
List<String> results = parser.parseExpression(expression)
.getValue(context, tesla, List.class);
----
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
----
// Create parser and evaluation context.
val parser = SpelExpressionParser()
val context = SimpleEvaluationContext.forReadWriteDataBinding().build()
// Create an inventor to use as the root context object.
val tesla = Inventor("Nikola Tesla")
tesla.setInventions("Telephone repeater", "Tesla coil transformer")
// Iterate over all inventions of the Inventor referenced as the #root
// object, and generate a list of strings whose contents take the form
// "<inventor's name> invented the <invention>." (using projection !{...}).
val expression = "#root.inventions.![#root.name + ' invented the ' + #this + '.']"
// Evaluates to a list containing:
// "Nikola Tesla invented the Telephone repeater."
// "Nikola Tesla invented the Tesla coil transformer."
val results = parser.parseExpression(expression)
.getValue(context, tesla, List::class.java)
----
======
@@ -429,7 +429,7 @@ Kotlin::
----
======
A `ConstraintViolation` on `Person.name()` is adapted to a `FieldErrro` with the following:
A `ConstraintViolation` on `Person.name()` is adapted to a `FieldError` with the following:
- Error codes `"Size.student.name"`, `"Size.name"`, `"Size.java.lang.String"`, and `"Size"`
- Message arguments `"name"`, `10`, and `1` (the field name and the constraint attributes)
@@ -230,6 +230,19 @@ provided you stick to the required connection lookup pattern. Note that JTA does
savepoints or custom isolation levels and has a different timeout mechanism but otherwise
exposes similar behavior in terms of JDBC resources and JDBC commit/rollback management.
For JTA-style lazy retrieval of actual resource connections, Spring provides a
corresponding `DataSource` proxy class for the target connection pool: see
{spring-framework-api}/jdbc/datasource/LazyConnectionDataSourceProxy.html[`LazyConnectionDataSourceProxy`].
This is particularly useful for potentially empty transactions without actual statement
execution (never fetching an actual resource in such a scenario), and also in front of
a routing `DataSource` which means to take the transaction-synchronized read-only flag
and/or isolation level into account (e.g. `IsolationLevelDataSourceRouter`).
`LazyConnectionDataSourceProxy` also provides special support for a read-only connection
pool to use during a read-only transaction, avoiding the overhead of switching the JDBC
Connection's read-only flag at the beginning and end of every transaction when fetching
it from the primary connection pool (which may be costly depending on the JDBC driver).
NOTE: As of 5.3, Spring provides an extended `JdbcTransactionManager` variant which adds
exception translation capabilities on commit/rollback (aligned with `JdbcTemplate`).
Where `DataSourceTransactionManager` will only ever throw `TransactionSystemException`
@@ -717,7 +717,7 @@ For example, with positional parameters:
public int countOfActorsByFirstName(String firstName) {
return this.jdbcClient.sql("select count(*) from t_actor where first_name = ?")
.param(firstName);
.param(firstName)
.query(Integer.class).single();
}
----
@@ -730,7 +730,7 @@ For example, with named parameters:
public int countOfActorsByFirstName(String firstName) {
return this.jdbcClient.sql("select count(*) from t_actor where first_name = :firstName")
.param("firstName", firstName);
.param("firstName", firstName)
.query(Integer.class).single();
}
----
@@ -759,8 +759,8 @@ With a required single object result:
[source,java,indent=0,subs="verbatim,quotes"]
----
Actor actor = this.jdbcClient.sql("select first_name, last_name from t_actor where id = ?",
.param(1212L);
Actor actor = this.jdbcClient.sql("select first_name, last_name from t_actor where id = ?")
.param(1212L)
.query(Actor.class)
.single();
----
@@ -769,8 +769,8 @@ With a `java.util.Optional` result:
[source,java,indent=0,subs="verbatim,quotes"]
----
Optional<Actor> actor = this.jdbcClient.sql("select first_name, last_name from t_actor where id = ?",
.param(1212L);
Optional<Actor> actor = this.jdbcClient.sql("select first_name, last_name from t_actor where id = ?")
.param(1212L)
.query(Actor.class)
.optional();
----
@@ -780,7 +780,7 @@ And for an update statement:
[source,java,indent=0,subs="verbatim,quotes"]
----
this.jdbcClient.sql("insert into t_actor (first_name, last_name) values (?, ?)")
.param("Leonor").param("Watling");
.param("Leonor").param("Watling")
.update();
----
@@ -789,7 +789,7 @@ Or an update statement with named parameters:
[source,java,indent=0,subs="verbatim,quotes"]
----
this.jdbcClient.sql("insert into t_actor (first_name, last_name) values (:firstName, :lastName)")
.param("firstName", "Leonor").param("lastName", "Watling");
.param("firstName", "Leonor").param("lastName", "Watling")
.update();
----
@@ -800,7 +800,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();
----
@@ -407,6 +407,12 @@ exposes the Hibernate transaction as a JDBC transaction if you have set up the p
`DataSource` for which the transactions are supposed to be exposed through the
`dataSource` property of the `HibernateTransactionManager` class.
For JTA-style lazy retrieval of actual resource connections, Spring provides a
corresponding `DataSource` proxy class for the target connection pool: see
{spring-framework-api}/jdbc/datasource/LazyConnectionDataSourceProxy.html[`LazyConnectionDataSourceProxy`].
This is particularly useful for Hibernate read-only transactions which can often
be processed from a local cache rather than hitting the database.
[[orm-hibernate-resources]]
== Comparing Container-managed and Locally Defined Resources
@@ -268,8 +268,8 @@ The actual JPA provider bootstrapping is handed off to the specified executor an
running in parallel, to the application bootstrap thread. The exposed `EntityManagerFactory`
proxy can be injected into other application components and is even able to respond to
`EntityManagerFactoryInfo` configuration inspection. However, once the actual JPA provider
is being accessed by other components (for example, calling `createEntityManager`), those calls
block until the background bootstrapping has completed. In particular, when you use
is being accessed by other components (for example, calling `createEntityManager`), those
calls block until the background bootstrapping has completed. In particular, when you use
Spring Data JPA, make sure to set up deferred bootstrapping for its repositories as well.
@@ -284,9 +284,9 @@ to a newly created `EntityManager` per operation, in effect making its usage thr
It is possible to write code against the plain JPA without any Spring dependencies, by
using an injected `EntityManagerFactory` or `EntityManager`. Spring can understand the
`@PersistenceUnit` and `@PersistenceContext` annotations both at the field and the method level
if a `PersistenceAnnotationBeanPostProcessor` is enabled. The following example shows a plain
JPA DAO implementation that uses the `@PersistenceUnit` annotation:
`@PersistenceUnit` and `@PersistenceContext` annotations both at the field and the method
level if a `PersistenceAnnotationBeanPostProcessor` is enabled. The following example
shows a plain JPA DAO implementation that uses the `@PersistenceUnit` annotation:
[tabs]
======
@@ -506,13 +506,20 @@ if you have not already done so, to get more detailed coverage of Spring's decla
The recommended strategy for JPA is local transactions through JPA's native transaction
support. Spring's `JpaTransactionManager` provides many capabilities known from local
JDBC transactions (such as transaction-specific isolation levels and resource-level
read-only optimizations) against any regular JDBC connection pool (no XA requirement).
read-only optimizations) against any regular JDBC connection pool, without requiring
a JTA transaction coordinator and XA-capable resources.
Spring JPA also lets a configured `JpaTransactionManager` expose a JPA transaction
to JDBC access code that accesses the same `DataSource`, provided that the registered
`JpaDialect` supports retrieval of the underlying JDBC `Connection`.
Spring provides dialects for the EclipseLink and Hibernate JPA implementations.
See the xref:data-access/orm/jpa.adoc#orm-jpa-dialect[next section] for details on the `JpaDialect` mechanism.
`JpaDialect` supports retrieval of the underlying JDBC `Connection`. Spring provides
dialects for the EclipseLink and Hibernate JPA implementations. See the
xref:data-access/orm/jpa.adoc#orm-jpa-dialect[next section] for details on `JpaDialect`.
For JTA-style lazy retrieval of actual resource connections, Spring provides a
corresponding `DataSource` proxy class for the target connection pool: see
{spring-framework-api}/jdbc/datasource/LazyConnectionDataSourceProxy.html[`LazyConnectionDataSourceProxy`].
This is particularly useful for JPA read-only transactions which can often
be processed from a local cache rather than hitting the database.
[[orm-jpa-dialect]]
@@ -440,12 +440,8 @@ Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
----
val tuples: MutableList<Array<Any>> = ArrayList()
tuples.add(arrayOf("John", 35))
tuples.add(arrayOf("Ann", 50))
client.sql("SELECT id, name, state FROM table WHERE age IN (:ages)")
.bind("tuples", arrayOf(35, 50))
.bind("ages", arrayOf(35, 50))
----
======
@@ -38,6 +38,11 @@ within the method.
A reactive transaction managed by `ReactiveTransactionManager` uses the Reactor context
instead of thread-local attributes. As a consequence, all participating data access
operations need to execute within the same Reactor context in the same reactive pipeline.
When configured with a `ReactiveTransactionManager`, all transaction-demarcated methods
are expected to return a reactive pipeline. Void methods or regular return types need
to be associated with a regular `PlatformTransactionManager`, e.g. through the
`transactionManager` attribute of the corresponding `@Transactional` declarations.
====
The following image shows a conceptual view of calling a method on a transactional proxy:
+2 -2
View File
@@ -18,7 +18,7 @@ WebSocket, RSocket.
xref:integration.adoc[Integration] :: REST Clients, JMS, JCA, JMX,
Email, Tasks, Scheduling, Caching, Observability, JVM Checkpoint Restore.
xref:languages.adoc[Languages] :: Kotlin, Groovy, Dynamic Languages.
xref:testing/appendix.adoc[Appendix] :: Spring properties.
xref:appendix.adoc[Appendix] :: Spring properties.
{spring-framework-wiki}[Wiki] :: What's New,
Upgrade Notes, Supported Versions, additional cross-version information.
@@ -29,7 +29,7 @@ Brannen, Ramnivas Laddad, Arjen Poutsma, Chris Beams, Tareq Abedrabbo, Andy Clem
Syer, Oliver Gierke, Rossen Stoyanchev, Phillip Webb, Rob Winch, Brian Clozel, Stephane
Nicoll, Sebastien Deleuze, Jay Bryant, Mark Paluch
Copyright © 2002 - 2023 VMware, Inc. All Rights Reserved.
Copyright © 2002 - 2024 VMware, Inc. All Rights Reserved.
Copies of this document may be made for your own use and for distribution to others,
provided that you do not charge any fee for such copies and further provided that each
@@ -1,5 +1,6 @@
[[class-data-sharing]]
= Class Data Sharing
[[cds]]
= CDS
:page-aliases: integration/class-data-sharing.adoc
Class Data Sharing (CDS) is a https://docs.oracle.com/en/java/javase/17/vm/class-data-sharing.html[JVM feature]
that can help reduce the startup time and memory footprint of Java applications.
@@ -19,7 +20,7 @@ been published.
To create the archive, two additional JVM flags must be specified:
* `-XX:ArchiveClassesAtExit=app-cds.jsa`: creates the CDS archive on exit
* `-XX:ArchiveClassesAtExit=application.jsa`: creates the CDS archive on exit
* `-Dspring.context.exit=onRefresh`: starts and then immediately exits your Spring
application as described above
@@ -40,8 +41,8 @@ The base CDS archive can be created by issuing the following command:
== Using the Archive
Once the archive is available, add `-XX:SharedArchiveFile=app-cds.jsa` to your startup
script to use it, assuming a `app-cds.jsa` file in the working directory.
Once the archive is available, add `-XX:SharedArchiveFile=application.jsa` to your startup
script to use it, assuming an `application.jsa` file in the working directory.
To figure out how effective the cache is, you can enable class loading logs by adding
an extra attribute: `-Xlog:class+load:file=cds.log`. This creates a `cds.log` with every
@@ -15,8 +15,7 @@ Conceptually, checkpoint and restore align with the xref:core/beans/factory-natu
== On-demand checkpoint/restore of a running application
A checkpoint can be created on demand, for example using a command like `jcmd application.jar JDK.checkpoint`. Before the creation of the checkpoint, Spring Framework
stops all the running beans, giving them a chance to close resources if needed by implementing `Lifecycle.stop`. After restore, the same beans are restarted, with `Lifecycle.start` allowing beans to reopen resources when relevant. For libraries that do not depend on Spring, custom checkpoint/restore integration can be provided by implementing `org.crac.Resource` and registering the related instance.
A checkpoint can be created on demand, for example using a command like `jcmd application.jar JDK.checkpoint`. Before the creation of the checkpoint, Spring stops all the running beans, giving them a chance to close resources if needed by implementing `Lifecycle.stop`. After restore, the same beans are restarted, with `Lifecycle.start` allowing beans to reopen resources when relevant. For libraries that do not depend on Spring, custom checkpoint/restore integration can be provided by implementing `org.crac.Resource` and registering the related instance.
WARNING: Leveraging checkpoint/restore of a running application typically requires additional lifecycle management to gracefully stop and start using resources like files or sockets and stop active threads.
@@ -29,6 +28,11 @@ startup during the `LifecycleProcessor.onRefresh` phase. After this phase has co
`InitializingBean#afterPropertiesSet` callbacks have been invoked; but the lifecycle has not started, and the
`ContextRefreshedEvent` has not yet been published.
For testing purposes, it is also possible to leverage the `-Dspring.context.exit=onRefresh` JVM system property which
triggers similar behavior, but instead of creating a checkpoint, it exits your Spring application at the same lifecycle
phase without requiring the Project CraC dependency/JVM or Linux. This can be useful to check if connections to remote
services are required when the beans are not started, and potentially refine the configuration to avoid that.
WARNING: As mentioned above, and especially in use cases where the CRaC files are shipped as part of a deployable artifact (a container image for example), operate with the assumption that any sensitive data "seen" by the JVM ends up in the CRaC files, and assess carefully the related security implications.
NOTE: Automatic checkpoint/restore is a way to "fast-forward" the startup of the application to a phase where the application context is about to start, but it does not allow to have a fully warmed-up JVM.
@@ -85,7 +85,7 @@ email when someone places an order:
// Call the collaborators to persist the order...
// Create a thread safe "copy" of the template message and customize it
// Create a thread-safe "copy" of the template message and customize it
SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
msg.setTo(order.getCustomer().getEmailAddress());
msg.setText(
@@ -108,7 +108,7 @@ By default, the following `KeyValues` are created:
|===
|Name | Description
|`code.function` _(required)_|Name of Java `Method` that is scheduled for execution.
|`code.namespace` _(required)_|Canonical name of the class of the bean instance that holds the scheduled method.
|`code.namespace` _(required)_|Canonical name of the class of the bean instance that holds the scheduled method, or `"ANONYMOUS"` for anonymous classes.
|`error` _(required)_|Class name of the exception thrown during the execution, or `"none"` if no exception happened.
|`exception` _(deprecated)_|Duplicates the `error` key and might be removed in the future.
|`outcome` _(required)_|Outcome of the method execution. Can be `"SUCCESS"`, `"ERROR"` or `"UNKNOWN"` (if for example the operation was cancelled during execution).
@@ -13,12 +13,12 @@ The Spring Framework provides the following choices for making calls to REST end
== `RestClient`
The `RestClient` is a synchronous HTTP client that offers a modern, fluent API.
It offers an abstraction over HTTP libraries that allows for convenient conversion from Java object to HTTP request, and creation of objects from the HTTP response.
It offers an abstraction over HTTP libraries that allows for convenient conversion from a Java object to an HTTP request, and the creation of objects from an HTTP response.
=== Creating a `RestClient`
The `RestClient` is created using one of the static `create` methods.
You can also use `builder` to get a builder with further options, such as specifying which HTTP library to use (see <<rest-request-factories>>) and which message converters to use (see <<rest-message-conversion>>), setting a default URI, default path variables, a default request headers, or `uriBuilderFactory`, or registering interceptors and initializers.
You can also use `builder()` to get a builder with further options, such as specifying which HTTP library to use (see <<rest-request-factories>>) and which message converters to use (see <<rest-message-conversion>>), setting a default URI, default path variables, default request headers, or `uriBuilderFactory`, or registering interceptors and initializers.
Once created (or built), the `RestClient` can be used safely by multiple threads.
@@ -51,9 +51,9 @@ val defaultClient = RestClient.create()
val customClient = RestClient.builder()
.requestFactory(HttpComponentsClientHttpRequestFactory())
.messageConverters(converters -> converters.add(MyCustomMessageConverter()))
.messageConverters { converters -> converters.add(MyCustomMessageConverter()) }
.baseUrl("https://example.com")
.defaultUriVariables(Map.of("variable", "foo"))
.defaultUriVariables(mapOf("variable" to "foo"))
.defaultHeader("My-Header", "Foo")
.requestInterceptor(myCustomInterceptor)
.requestInitializer(myCustomInitializer)
@@ -64,35 +64,36 @@ val customClient = RestClient.builder()
=== Using the `RestClient`
When making an HTTP request with the `RestClient`, the first thing to specify is which HTTP method to use.
This can be done with `method(HttpMethod)`, or with the convenience methods `get()`, `head()`, `post()`, and so on.
This can be done with `method(HttpMethod)` or with the convenience methods `get()`, `head()`, `post()`, and so on.
==== Request URL
Next, the request URI can be specified with the `uri` methods.
This step is optional, and can be skipped if the `RestClient` is configured with a default URI.
The URL is typically specified as `String`, with optional URI template variables.
This step is optional and can be skipped if the `RestClient` is configured with a default URI.
The URL is typically specified as a `String`, with optional URI template variables.
String URLs are encoded by default, but this can be changed by building a client with a custom `uriBuilderFactory`.
The URL can also be provided with a function, or as `java.net.URI`, both of which are not encoded.
The URL can also be provided with a function or as a `java.net.URI`, both of which are not encoded.
For more details on working with and encoding URIs, see xref:web/webmvc/mvc-uri-building.adoc[URI Links].
==== Request headers and body
If necessary, the HTTP request can be manipulated, by adding request headers with `header(String, String)`, `headers(Consumer<HttpHeaders>`, or with the convenience methods `accept(MediaType...)`, `acceptCharset(Charset...)` and so on.
For HTTP request that can contain a body (`POST`, `PUT`, and `PATCH`), additional methods are available: `contentType(MediaType)`, and `contentLength(long)`.
If necessary, the HTTP request can be manipulated by adding request headers with `header(String, String)`, `headers(Consumer<HttpHeaders>`, or with the convenience methods `accept(MediaType...)`, `acceptCharset(Charset...)` and so on.
For HTTP requests that can contain a body (`POST`, `PUT`, and `PATCH`), additional methods are available: `contentType(MediaType)`, and `contentLength(long)`.
The request body itself can be set by `body(Object)`, which internally uses <<rest-message-conversion>>.
Alternatively, the request body can be set using a `ParameterizedTypeReference`, allowing you to use generics.
Finally, the body can be set to a callback function that writes to an `OutputStream`.
==== Retrieving the response
Once the request has been set up, the HTTP response is accessed by invoking `retrieve()`.
The response body can be accessed by using `body(Class)`, or `body(ParameterizedTypeReference)` for parameterized types like lists.
The `body` method converts the response contents into various types, for instance bytes can be converted into a `String`, JSON into objects using Jackson, and so on (see <<rest-message-conversion>>).
The response body can be accessed by using `body(Class)` or `body(ParameterizedTypeReference)` for parameterized types like lists.
The `body` method converts the response contents into various types for instance, bytes can be converted into a `String`, JSON can be converted into objects using Jackson, and so on (see <<rest-message-conversion>>).
The response can also be converted into a `ResponseEntity`, giving access to the response headers as well as the body.
This sample shows how `RestClient` can be used to perform a simple GET request.
This sample shows how `RestClient` can be used to perform a simple `GET` request.
[tabs]
======
@@ -171,7 +172,7 @@ println("Contents: " + result.body) <3>
======
`RestClient` can convert JSON to objects, using the Jackson library.
Note the usage of uri variables in this sample, and that the `Accept` header is set to JSON.
Note the usage of URI variables in this sample and that the `Accept` header is set to JSON.
[tabs]
======
@@ -248,8 +249,9 @@ val response = restClient.post() <2>
======
==== Error handling
By default, `RestClient` throws a subclass of `RestClientException` when retrieving a response with a 4xx or 5xx status code.
This behavior can be overriden using `onStatus`.
This behavior can be overridden using `onStatus`.
[tabs]
======
@@ -286,8 +288,9 @@ val result = restClient.get() <1>
======
==== Exchange
For more advanced scenarios, the `RestClient` gives access to the underlying HTTP request and response through the `exchange` method, which can be used instead of `retrieve()`.
Status handlers are not applied when you exchange, because the exchange function already provides access to the full response, allowing you to perform any error handling necessary.
For more advanced scenarios, the `RestClient` gives access to the underlying HTTP request and response through the `exchange()` method, which can be used instead of `retrieve()`.
Status handlers are not applied when use `exchange()`, because the exchange function already provides access to the full response, allowing you to perform any error handling necessary.
[tabs]
======
@@ -336,6 +339,7 @@ val result = restClient.get()
[[rest-message-conversion]]
=== HTTP Message Conversion
[.small]#xref:web/webflux/reactive-spring.adoc#webflux-codecs[See equivalent in the Reactive stack]#
The `spring-web` module contains the `HttpMessageConverter` interface for reading and writing the body of HTTP requests and responses through `InputStream` and `OutputStream`.
@@ -397,7 +401,7 @@ By default, this converter supports `text/xml` and `application/xml`.
|===
By default, `RestClient` and `RestTemplate` register all built-in message converters, depending on the availability of underlying libraries on the classpath.
You can also set the message converters to use explicitly, by using `messageConverters` on the `RestClient` builder, or via the `messageConverters` property of `RestTemplate`.
You can also set the message converters to use explicitly, by using the `messageConverters()` method on the `RestClient` builder, or via the `messageConverters` property of `RestTemplate`.
==== Jackson JSON Views
@@ -437,13 +441,13 @@ parts.add("xmlPart", new HttpEntity<>(myBean, headers));
----
In most cases, you do not have to specify the `Content-Type` for each part.
The content type is determined automatically based on the `HttpMessageConverter` chosen to serialize it or, in the case of a `Resource` based on the file extension.
The content type is determined automatically based on the `HttpMessageConverter` chosen to serialize it or, in the case of a `Resource`, based on the file extension.
If necessary, you can explicitly provide the `MediaType` with an `HttpEntity` wrapper.
Once the `MultiValueMap` is ready, you can use it as the body of a POST request, using `RestClient.post().body(parts)` (or `RestTemplate.postForObject`).
Once the `MultiValueMap` is ready, you can use it as the body of a `POST` request, using `RestClient.post().body(parts)` (or `RestTemplate.postForObject`).
If the `MultiValueMap` contains at least one non-`String` value, the `Content-Type` is set to `multipart/form-data` by the `FormHttpMessageConverter`.
If the `MultiValueMap` has `String` values the `Content-Type` defaults to `application/x-www-form-urlencoded`.
If the `MultiValueMap` has `String` values, the `Content-Type` defaults to `application/x-www-form-urlencoded`.
If necessary the `Content-Type` may also be set explicitly.
[[rest-request-factories]]
@@ -453,11 +457,11 @@ To execute the HTTP request, `RestClient` uses a client HTTP library.
These libraries are adapted via the `ClientRequestFactory` interface.
Various implementations are available:
* `JdkClientHttpRequestFactory` for Java's `HttpClient`,
* `HttpComponentsClientHttpRequestFactory` for use with Apache HTTP Components `HttpClient`,
* `JettyClientHttpRequestFactory` for Jetty's `HttpClient`,
* `ReactorNettyClientRequestFactory` for Reactor Netty's `HttpClient`,
* `SimpleClientHttpRequestFactory` as a simple default.
* `JdkClientHttpRequestFactory` for Java's `HttpClient`
* `HttpComponentsClientHttpRequestFactory` for use with Apache HTTP Components `HttpClient`
* `JettyClientHttpRequestFactory` for Jetty's `HttpClient`
* `ReactorNettyClientRequestFactory` for Reactor Netty's `HttpClient`
* `SimpleClientHttpRequestFactory` as a simple default
If no request factory is specified when the `RestClient` was built, it will use the Apache or Jetty `HttpClient` if they are available on the classpath.
@@ -473,12 +477,12 @@ synchronous, asynchronous, and streaming scenarios.
`WebClient` supports the following:
* Non-blocking I/O.
* Reactive Streams back pressure.
* High concurrency with fewer hardware resources.
* Functional-style, fluent API that takes advantage of Java 8 lambdas.
* Synchronous and asynchronous interactions.
* Streaming up to or streaming down from a server.
* Non-blocking I/O
* Reactive Streams back pressure
* High concurrency with fewer hardware resources
* Functional-style, fluent API that takes advantage of Java 8 lambdas
* Synchronous and asynchronous interactions
* Streaming up to or streaming down from a server
See xref:web/webflux-webclient.adoc[WebClient] for more details.
@@ -848,17 +852,17 @@ It can be used to migrate from the latter to the former.
.toEntity(ParameterizedTypeReference)` footnote:request-entity[]
| `execute(String, HttpMethod method, RequestCallback, ResponseExtractor, Object...)`
| `execute(String, HttpMethod, RequestCallback, ResponseExtractor, Object...)`
| `method(HttpMethod)
.uri(String, Object...)
.exchange(ExchangeFunction)`
| `execute(String, HttpMethod method, RequestCallback, ResponseExtractor, Map)`
| `execute(String, HttpMethod, RequestCallback, ResponseExtractor, Map)`
| `method(HttpMethod)
.uri(String, Map)
.exchange(ExchangeFunction)`
| `execute(URI, HttpMethod method, RequestCallback, ResponseExtractor)`
| `execute(URI, HttpMethod, RequestCallback, ResponseExtractor)`
| `method(HttpMethod)
.uri(URI)
.exchange(ExchangeFunction)`
@@ -906,8 +910,8 @@ For `WebClient`:
[source,java,indent=0,subs="verbatim,quotes"]
----
WebClient client = WebClient.builder().baseUrl("https://api.github.com/").build();
WebClientAdapter adapter = WebClientAdapter.forClient(webClient)
WebClient webClient = WebClient.builder().baseUrl("https://api.github.com/").build();
WebClientAdapter adapter = WebClientAdapter.create(webClient);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();
RepositoryService service = factory.createClient(RepositoryService.class);
@@ -973,6 +977,9 @@ method parameters:
`Map<String, ?>` with multiple variables, or an individual value. Type conversion
is supported for non-String values.
| `@RequestAttribute`
| Provide an `Object` to add as a request attribute. Only supported by `WebClient`.
| `@RequestBody`
| Provide the body of the request either as an Object to be serialized, or a
Reactive Streams `Publisher` such as `Mono`, `Flux`, or any other async type supported
@@ -1078,11 +1085,34 @@ underlying HTTP client, which operates at a lower level and provides more contro
[[rest-http-interface-exceptions]]
=== Exception Handling
=== Error Handling
By default, `WebClient` raises `WebClientResponseException` for 4xx and 5xx HTTP status
codes. To customize this, you can register a response status handler that applies to all
responses performed through the client:
To customize error response handling, you need to configure the underlying HTTP client.
For `RestClient`:
By default, `RestClient` raises `RestClientException` for 4xx and 5xx HTTP status codes.
To customize this, register a response status handler that applies to all responses
performed through the client:
[source,java,indent=0,subs="verbatim,quotes"]
----
RestClient restClient = RestClient.builder()
.defaultStatusHandler(HttpStatusCode::isError, (request, response) -> ...)
.build();
RestClientAdapter adapter = RestClientAdapter.create(restClient);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();
----
For more details and options, such as suppressing error status codes, see the Javadoc of
`defaultStatusHandler` in `RestClient.Builder`.
For `WebClient`:
By default, `WebClient` raises `WebClientResponseException` for 4xx and 5xx HTTP status codes.
To customize this, register a response status handler that applies to all responses
performed through the client:
[source,java,indent=0,subs="verbatim,quotes"]
----
@@ -1090,10 +1120,28 @@ responses performed through the client:
.defaultStatusHandler(HttpStatusCode::isError, resp -> ...)
.build();
WebClientAdapter clientAdapter = WebClientAdapter.forClient(webClient);
HttpServiceProxyFactory factory = HttpServiceProxyFactory
.builder(clientAdapter).build();
WebClientAdapter adapter = WebClientAdapter.create(webClient);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builder(adapter).build();
----
For more details and options, such as suppressing error status codes, see the Javadoc of
`defaultStatusHandler` in `WebClient.Builder`.
For `RestTemplate`:
By default, `RestTemplate` raises `RestClientException` for 4xx and 5xx HTTP status codes.
To customize this, register an error handler that applies to all responses
performed through the client:
[source,java,indent=0,subs="verbatim,quotes"]
----
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(myErrorHandler);
RestTemplateAdapter adapter = RestTemplateAdapter.create(restTemplate);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();
----
For more details and options, see the Javadoc of `setErrorHandler` in `RestTemplate` and
the `ResponseErrorHandler` hierarchy.
@@ -252,7 +252,9 @@ application server environments, as well -- in particular on Tomcat and Jetty.
As of 6.1, `ThreadPoolTaskScheduler` provides a pause/resume capability and graceful
shutdown through Spring's lifecycle management. There is also a new option called
`SimpleAsyncTaskScheduler` which is aligned with JDK 21's Virtual Threads, using a
single scheduler thread but firing up a new thread for every scheduled task execution.
single scheduler thread but firing up a new thread for every scheduled task execution
(except for fixed-delay tasks which all operate on a single scheduler thread, so for
this virtual-thread-aligned option, fixed rates and cron triggers are recommended).
@@ -477,12 +479,12 @@ the framework to invoke a suspending function as a `Publisher`.
The Spring Framework will obtain a `Publisher` for the annotated method once and will
schedule a `Runnable` in which it subscribes to said `Publisher`. These inner regular
subscriptions occur according to the corresponding `cron`/fixedDelay`/`fixedRate` configuration.
subscriptions occur according to the corresponding `cron`/`fixedDelay`/`fixedRate` configuration.
If the `Publisher` emits `onNext` signal(s), these are ignored and discarded (the same way
return values from synchronous `@Scheduled` methods are ignored).
In the following example, the `Flux` emits `onNext("Hello"), onNext("World")` every 5
In the following example, the `Flux` emits `onNext("Hello")`, `onNext("World")` every 5
seconds, but these values are unused:
[source,java,indent=0,subs="verbatim,quotes"]
@@ -13,7 +13,7 @@ Most of the code samples of the reference documentation are
provided in Kotlin in addition to Java.
The easiest way to build a Spring application with Kotlin is to leverage Spring Boot and
its{spring-boot-docs}/boot-features-kotlin.html[dedicated Kotlin support].
its {spring-boot-docs}/boot-features-kotlin.html[dedicated Kotlin support].
{spring-site-guides}/tutorials/spring-boot-kotlin/[This comprehensive tutorial]
will teach you how to build Spring Boot applications with Kotlin using https://start.spring.io/#!language=kotlin&type=gradle-project[start.spring.io].
@@ -107,7 +107,7 @@ NOTE: Spring Boot is based on JavaConfig and
{spring-boot-issues}/8115[does not yet provide specific support for functional bean definition],
but you can experimentally use functional bean definitions through Spring Boot's `ApplicationContextInitializer` support.
See {stackoverflow-questions}/45935931/how-to-use-functional-bean-definition-kotlin-dsl-with-spring-boot-and-spring-w/46033685#46033685[this Stack Overflow answer]
for more details and up-to-date information. See also the experimental Kofu DSL developed in {spring-github-org}/spring-fu[Spring Fu incubator].
for more details and up-to-date information. See also the experimental Kofu DSL developed in {spring-github-org}-experimental/spring-fu[Spring Fu incubator].
@@ -14,8 +14,10 @@ Spring Framework provides support for Coroutines on the following scope:
* Suspending function support in Spring MVC and WebFlux annotated `@Controller`
* Extensions for WebFlux {spring-framework-api-kdoc}/spring-webflux/org.springframework.web.reactive.function.client/index.html[client] and {spring-framework-api-kdoc}/spring-webflux/org.springframework.web.reactive.function.server/index.html[server] functional API.
* WebFlux.fn {spring-framework-api-kdoc}/spring-webflux/org.springframework.web.reactive.function.server/co-router.html[coRouter { }] DSL
* WebFlux {spring-framework-api-kdoc}/spring-web/org.springframework.web.server/-co-web-filter/index.html[`CoWebFilter`]
* Suspending function and `Flow` support in RSocket `@MessageMapping` annotated methods
* Extensions for {spring-framework-api-kdoc}/spring-messaging/org.springframework.messaging.rsocket/index.html[`RSocketRequester`]
* Spring AOP
@@ -10,22 +10,21 @@ The easiest way to learn how to build a Spring application with Kotlin is to fol
== `start.spring.io`
The easiest way to start a new Spring Framework project in Kotlin is to create a new Spring
Boot 2 project on https://start.spring.io/#!language=kotlin&type=gradle-project[start.spring.io].
Boot project on https://start.spring.io/#!language=kotlin&type=gradle-project-kotlin[start.spring.io].
[[choosing-the-web-flavor]]
== Choosing the Web Flavor
Spring Framework now comes with two different web stacks: xref:web/webmvc.adoc#mvc[Spring MVC] and
Spring Framework comes with two different web stacks: xref:web/webmvc.adoc#mvc[Spring MVC] and
xref:testing/unit.adoc#mock-objects-web-reactive[Spring WebFlux].
Spring WebFlux is recommended if you want to create applications that will deal with latency,
long-lived connections, streaming scenarios or if you want to use the web functional
Kotlin DSL.
long-lived connections or streaming scenarios.
For other use cases, especially if you are using blocking technologies such as JPA, Spring
MVC and its annotation-based programming model is the recommended choice.
MVC is the recommended choice.
@@ -2,15 +2,12 @@
= Requirements
:page-section-summary-toc: 1
Spring Framework supports Kotlin 1.3+ and requires
Spring Framework supports Kotlin 1.7+ and requires
https://search.maven.org/artifact/org.jetbrains.kotlin/kotlin-stdlib[`kotlin-stdlib`]
(or one of its variants, such as https://search.maven.org/artifact/org.jetbrains.kotlin/kotlin-stdlib-jdk8[`kotlin-stdlib-jdk8`])
and https://search.maven.org/artifact/org.jetbrains.kotlin/kotlin-reflect[`kotlin-reflect`]
to be present on the classpath. They are provided by default if you bootstrap a Kotlin project on
https://start.spring.io/#!language=kotlin&type=gradle-project[start.spring.io].
WARNING: Kotlin {kotlin-docs}/inline-classes.html[inline classes] are not yet supported.
NOTE: The {jackson-github-org}/jackson-module-kotlin[Jackson Kotlin module] is required
for serializing or deserializing JSON data for Kotlin classes with Jackson, so make sure to add the
`com.fasterxml.jackson.module:jackson-module-kotlin` dependency to your project if you have such need.
@@ -18,28 +18,9 @@ Kotlin and the Spring Framework:
The following Github projects offer examples that you can learn from and possibly even extend:
* https://github.com/spring-guides/tut-spring-boot-kotlin[tut-spring-boot-kotlin]: Sources of {spring-site}/guides/tutorials/spring-boot-kotlin/[the official Spring + Kotlin tutorial]
* https://github.com/sdeleuze/spring-boot-kotlin-demo[spring-boot-kotlin-demo]: Regular Spring Boot and Spring Data JPA project
* https://github.com/mixitconf/mixit[mixit]: Spring Boot 2, WebFlux, and Reactive Spring Data MongoDB
* https://github.com/mixitconf/mixit[mixit]: Spring Boot, WebFlux, and Reactive Spring Data MongoDB
* https://github.com/sdeleuze/spring-kotlin-functional[spring-kotlin-functional]: Standalone WebFlux and functional bean definition DSL
* https://github.com/sdeleuze/spring-kotlin-fullstack[spring-kotlin-fullstack]: WebFlux Kotlin fullstack example with Kotlin2js for frontend instead of JavaScript or TypeScript
* https://github.com/spring-petclinic/spring-petclinic-kotlin[spring-petclinic-kotlin]: Kotlin version of the Spring PetClinic Sample Application
* https://github.com/sdeleuze/spring-kotlin-deepdive[spring-kotlin-deepdive]: A step-by-step migration guide for Boot 1.0 and Java to Boot 2.0 and Kotlin
* https://github.com/spring-cloud/spring-cloud-gcp/tree/master/spring-cloud-gcp-kotlin-samples/spring-cloud-gcp-kotlin-app-sample[spring-cloud-gcp-kotlin-app-sample]: Spring Boot with Google Cloud Platform Integrations
[[issues]]
== Issues
The following list categorizes the pending issues related to Spring and Kotlin support:
* Spring Framework
** {spring-framework-issues}/20606[Unable to use WebTestClient with mock server in Kotlin]
** {spring-framework-issues}/20496[Support null-safety at generics, varargs and array elements level]
* Kotlin
** {kotlin-issues}/KT-6380[Parent issue for Spring Framework support]
** {kotlin-issues}/KT-5464[Kotlin requires type inference where Java doesn't]
** {kotlin-issues}/KT-20283[Smart cast regression with open classes]
** {kotlin-issues}/KT-14984[Impossible to pass not all SAM argument as function]
** {kotlin-issues}/KT-15125[Support JSR 223 bindings directly via script variables]
** {kotlin-issues}/KT-6653[Kotlin properties do not override Java-style getters and setters]
@@ -9,7 +9,7 @@ in Kotlin.
[[final-by-default]]
== Final by Default
By default, https://discuss.kotlinlang.org/t/classes-final-by-default/166[all classes in Kotlin are `final`].
By default, https://discuss.kotlinlang.org/t/classes-final-by-default/166[all classes and member functions in Kotlin are `final`].
The `open` modifier on a class is the opposite of Java's `final`: It allows others to inherit from this
class. This also applies to member functions, in that they need to be marked as `open` to be overridden.
@@ -38,6 +38,12 @@ Meta-annotation support means that types annotated with `@Configuration`, `@Cont
`@RestController`, `@Service`, or `@Repository` are automatically opened since these
annotations are meta-annotated with `@Component`.
WARNING: Some use cases involving proxies and automatic generation of final methods by the Kotlin compiler require extra
care. For example, a Kotlin class with properties will generate related `final` getters and setters. In order
to be able to proxy related methods, a type level `@Component` annotation should be preferred to method level `@Bean` in
order to have those methods opened by the `kotlin-spring` plugin. A typical use case is `@Scope` and its popular
`@RequestScope` specialization.
https://start.spring.io/#!language=kotlin&type=gradle-project[start.spring.io] enables
the `kotlin-spring` plugin by default. So, in practice, you can write your Kotlin beans
without any additional `open` keyword, as in Java.
@@ -97,6 +103,9 @@ does not require the `kotlin-noarg` plugin if the module uses Spring Data object
[[injecting-dependencies]]
== Injecting Dependencies
[[favor-constructor-injection]]
=== Favor constructor injection
Our recommendation is to try to favor constructor injection with `val` read-only (and
non-nullable when possible) {kotlin-docs}/properties.html[properties],
as the following example shows:
@@ -130,7 +139,41 @@ as the following example shows:
}
----
[[internal-functions-name-mangling]]
=== Internal functions name mangling
Kotlin functions with the `internal` {kotlin-docs}/visibility-modifiers.html#class-members[visibility modifier] have
their names mangled when compiled to JVM bytecode, which has a side effect when injecting dependencies by name.
For example, this Kotlin class:
[source,kotlin,indent=0]
----
@Configuration
class SampleConfiguration {
@Bean
internal fun sampleBean() = SampleBean()
}
----
Translates to this Java representation of the compiled JVM bytecode:
[source,java,indent=0]
----
@Configuration
@Metadata(/* ... */)
public class SampleConfiguration {
@Bean
@NotNull
public SampleBean sampleBean$demo_kotlin_internal_test() {
return new SampleBean();
}
}
----
As a consequence, the related bean name represented as a Kotlin string is `"sampleBean\$demo_kotlin_internal_test"`,
instead of `"sampleBean"` for the regular `public` function use-case. Make sure to use the mangled name when injecting
such bean by name, or add `@JvmName("sampleBean")` to disable name mangling.
[[injecting-configuration-properties]]
== Injecting Configuration Properties
@@ -8,9 +8,9 @@
Spring Framework comes with a Kotlin router DSL available in 3 flavors:
* WebMvc.fn DSL with {spring-framework-api-kdoc}/spring-webmvc/org.springframework.web.servlet.function/router.html[router { }]
* WebFlux.fn <<web-reactive#webflux-fn, Reactive>> DSL with {spring-framework-api-kdoc}/spring-webflux/org.springframework.web.reactive.function.server/router.html[router { }]
* WebFlux.fn <<Coroutines>> DSL with {spring-framework-api-kdoc}/spring-webflux/org.springframework.web.reactive.function.server/co-router.html[coRouter { }]
* xref:web/webmvc-functional.adoc[WebMvc.fn DSL] with {spring-framework-api-kdoc}/spring-webmvc/org.springframework.web.servlet.function/router.html[router { }]
* xref:web/webflux-functional.adoc[WebFlux.fn Reactive DSL] with {spring-framework-api-kdoc}/spring-webflux/org.springframework.web.reactive.function.server/router.html[router { }]
* xref:languages/kotlin/coroutines.adoc[WebFlux.fn Coroutines DSL] with {spring-framework-api-kdoc}/spring-webflux/org.springframework.web.reactive.function.server/co-router.html[coRouter { }]
These DSL let you write clean and idiomatic Kotlin code to build a `RouterFunction` instance as the following example shows:
@@ -126,7 +126,7 @@ project for more details.
[[kotlin-multiplatform-serialization]]
== Kotlin multiplatform serialization
As of Spring Framework 5.3, {kotlin-github-org}/kotlinx.serialization[Kotlin multiplatform serialization] is
{kotlin-github-org}/kotlinx.serialization[Kotlin multiplatform serialization] is
supported in Spring MVC, Spring WebFlux and Spring Messaging (RSocket). The builtin support currently targets CBOR, JSON, and ProtoBuf formats.
To enable it, follow {kotlin-github-org}/kotlinx.serialization#setup[those instructions] to add the related dependency and plugin.
@@ -152,7 +152,7 @@ Kotlin::
@Autowired
lateinit var accountService: AccountService
lateinit mockMvc: MockMvc
lateinit var mockMvc: MockMvc
@BeforeEach
fun setup(wac: WebApplicationContext) {
@@ -45,7 +45,7 @@ xref:appendix.adoc#appendix-spring-properties[`SpringProperties`] mechanism.
[NOTE]
====
The `@ContextHierarchy` annotation is currently not supported in AOT mode.
The `@ContextHierarchy` annotation is not supported in AOT mode.
====
To provide test-specific runtime hints for use within a GraalVM native image, you have
@@ -42,13 +42,15 @@ become cumbersome if a custom factory needs to be used across an entire test sui
issue is addressed through support for automatic discovery of default
`ContextCustomizerFactory` implementations through the `SpringFactoriesLoader` mechanism.
Specifically, the modules that make up the testing support in Spring Framework and Spring
For example, the modules that make up the testing support in Spring Framework and Spring
Boot declare all core default `ContextCustomizerFactory` implementations under the
`org.springframework.test.context.ContextCustomizerFactory` key in their
`META-INF/spring.factories` properties files. Third-party frameworks and developers can
contribute their own `ContextCustomizerFactory` implementations to the list of default
factories in the same manner through their own `META-INF/spring.factories` properties
files.
`META-INF/spring.factories` properties files. The `spring.factories` file for the
`spring-test` module can be viewed
{spring-framework-code}/spring-test/src/main/resources/META-INF/spring.factories[here].
Third-party frameworks and developers can contribute their own `ContextCustomizerFactory`
implementations to the list of default factories in the same manner through their own
`spring.factories` files.
[[testcontext-context-customizers-merging]]
@@ -80,12 +80,12 @@ become cumbersome if a custom listener needs to be used across an entire test su
issue is addressed through support for automatic discovery of default
`TestExecutionListener` implementations through the `SpringFactoriesLoader` mechanism.
Specifically, the `spring-test` module declares all core default `TestExecutionListener`
For example, the `spring-test` module declares all core default `TestExecutionListener`
implementations under the `org.springframework.test.context.TestExecutionListener` key in
its `META-INF/spring.factories` properties file. Third-party frameworks and developers
can contribute their own `TestExecutionListener` implementations to the list of default
listeners in the same manner through their own `META-INF/spring.factories` properties
file.
its {spring-framework-code}/spring-test/src/main/resources/META-INF/spring.factories[`META-INF/spring.factories`
properties file]. Third-party frameworks and developers can contribute their own
`TestExecutionListener` implementations to the list of default listeners in the same
manner through their own `spring.factories` files.
[[testcontext-tel-config-ordering]]
== Ordering `TestExecutionListener` Implementations
@@ -207,4 +207,3 @@ Kotlin::
}
----
======
@@ -782,6 +782,73 @@ Kotlin::
======
[[webflux-fn-serving-resources]]
== Serving Resources
WebFlux.fn provides built-in support for serving resources.
NOTE: In addition to the capabilities described below, it is possible to implement even more flexible resource handling thanks to
{spring-framework-api}++/web/reactive/function/server/RouterFunctions.html#resources(java.util.function.Function)++[`RouterFunctions#resource(java.util.function.Function)`].
[[webflux-fn-resource]]
=== Redirecting to a resource
It is possible to redirect requests matching a specified predicate to a resource. This can be useful, for example,
for handling redirects in Single Page Applications.
[tabs]
======
Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
ClassPathResource index = new ClassPathResource("static/index.html");
List<String> extensions = Arrays.asList("js", "css", "ico", "png", "jpg", "gif");
RequestPredicate spaPredicate = path("/api/**").or(path("/error")).or(pathExtension(extensions::contains)).negate();
RouterFunction<ServerResponse> redirectToIndex = route()
.resource(spaPredicate, index)
.build();
----
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
----
val redirectToIndex = router {
val index = ClassPathResource("static/index.html")
val extensions = listOf("js", "css", "ico", "png", "jpg", "gif")
val spaPredicate = !(path("/api/**") or path("/error") or
pathExtension(extensions::contains))
resource(spaPredicate, index)
}
----
======
[[webflux-fn-resources]]
=== Serving resources from a root location
It is also possible to route requests that match a given pattern to resources relative to a given root location.
[tabs]
======
Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
Resource location = new FileSystemResource("public-resources/");
RouterFunction<ServerResponse> resources = RouterFunctions.resources("/resources/**", location);
----
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
----
val location = FileSystemResource("public-resources/")
val resources = router { resources("/resources/**", location) }
----
======
[[webflux-fn-running]]
== Running a Server
[.small]#xref:web/webmvc-functional.adoc#webmvc-fn-running[See equivalent in the Servlet stack]#
@@ -198,6 +198,9 @@ 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]
_AND_ that is not resolved by any other argument resolver is treated as an `@ModelAttribute`.
_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`
support described above does not allow proper ahead-of-time inference of related data
binding reflection hints. As a consequence, it is recommended to explicitly annotate
method parameters with `@ModelAttribute` for use in a GraalVM native image.
@@ -28,6 +28,12 @@ because, arguably, most controller methods should be mapped to a specific HTTP m
using `@RequestMapping`, which, by default, matches to all HTTP methods. At the same time, a
`@RequestMapping` is still needed at the class level to express shared mappings.
NOTE: `@RequestMapping` cannot be used in conjunction with other `@RequestMapping`
annotations that are declared on the same element (class, interface, or method). If
multiple `@RequestMapping` annotations are detected on the same element, a warning will
be logged, and only the first mapping will be used. This also applies to composed
`@RequestMapping` annotations such as `@GetMapping`, `@PostMapping`, etc.
The following example uses type and method level mappings:
[tabs]
@@ -436,8 +442,14 @@ attributes with a narrower, more specific purpose.
`@GetMapping`, `@PostMapping`, `@PutMapping`, `@DeleteMapping`, and `@PatchMapping` are
examples of composed annotations. They are provided, because, arguably, most
controller methods should be mapped to a specific HTTP method versus using `@RequestMapping`,
which, by default, matches to all HTTP methods. If you need an example of composed
annotations, look at how those are declared.
which, by default, matches to all HTTP methods. If you need an example of how to implement
a composed annotation, look at how those are declared.
NOTE: `@RequestMapping` cannot be used in conjunction with other `@RequestMapping`
annotations that are declared on the same element (class, interface, or method). If
multiple `@RequestMapping` annotations are detected on the same element, a warning will
be logged, and only the first mapping will be used. This also applies to composed
`@RequestMapping` annotations such as `@GetMapping`, `@PostMapping`, etc.
Spring WebFlux also supports custom request mapping attributes with custom request matching
logic. This is a more advanced option that requires sub-classing
@@ -509,12 +521,19 @@ Kotlin::
[[webflux-ann-httpexchange-annotation]]
== `@HttpExchange`
[.small]#xref:web/webmvc/mvc-controller/ann-requestmapping.adoc#mvc-ann-httpexchange-annotation[See equivalent in the Reactive stack]#
[.small]#xref:web/webmvc/mvc-controller/ann-requestmapping.adoc#mvc-ann-httpexchange-annotation[See equivalent in the Servlet stack]#
As an alternative to `@RequestMapping`, you can also handle requests with `@HttpExchange`
methods. Such methods are declared on an
xref:integration/rest-clients.adoc#rest-http-interface[HTTP Interface] and can be used as
a client via `HttpServiceProxyFactory` or implemented by a server `@Controller`.
While the main purpose of `@HttpExchange` is to abstract HTTP client code with a
generated proxy, the
xref:integration/rest-clients.adoc#rest-http-interface[HTTP Interface] on which
such annotations are placed is a contract neutral to client vs server use.
In addition to simplifying client code, there are also cases where an HTTP Interface
may be a convenient way for servers to expose their API for client access. This leads
to increased coupling between client and server and is often not a good choice,
especially for public API's, but may be exactly the goal for an internal API.
It is an approach commonly used in Spring Cloud, and it is why `@HttpExchange` is
supported as an alternative to `@RequestMapping` for server side handling in
controller classes.
For example:
@@ -524,16 +543,23 @@ Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
@RestController
@HttpExchange("/persons")
class PersonController {
interface PersonService {
@GetExchange("/{id}")
Person getPerson(@PathVariable Long id);
@PostExchange
void add(@RequestBody Person person);
}
@RestController
class PersonController implements PersonService {
public Person getPerson(@PathVariable Long id) {
// ...
}
@PostExchange
@ResponseStatus(HttpStatus.CREATED)
public void add(@RequestBody Person person) {
// ...
@@ -545,30 +571,38 @@ Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
----
@RestController
@HttpExchange("/persons")
class PersonController {
interface PersonService {
@GetExchange("/{id}")
fun getPerson(@PathVariable id: Long): Person {
fun getPerson(@PathVariable id: Long): Person
@PostExchange
fun add(@RequestBody person: Person)
}
@RestController
class PersonController : PersonService {
override fun getPerson(@PathVariable id: Long): Person {
// ...
}
@PostExchange
@ResponseStatus(HttpStatus.CREATED)
fun add(@RequestBody person: Person) {
override fun add(@RequestBody person: Person) {
// ...
}
}
----
======
There some differences between `@HttpExchange` and `@RequestMapping` since the
former needs to remain suitable for client and server use. For example, while
`@RequestMapping` can be declared to handle any number of paths and each path can
be a pattern, `@HttpExchange` must be declared with a single, concrete path. There are
also differences in the supported method parameters. Generally, `@HttpExchange` supports
a subset of method parameters that `@RequestMapping` does, excluding any parameters that
are server side only. For details see the list of supported method parameters for
xref:integration/rest-clients.adoc#rest-http-interface-method-parameters[HTTP interface] and for
`@HttpExchange` and `@RequestMapping` have differences.
`@RequestMapping` can map to any number of requests by path patterns, HTTP methods,
and more, while `@HttpExchange` declares a single endpoint with a concrete HTTP method,
path, and content types.
For method parameters and returns values, generally, `@HttpExchange` supports a
subset of the method parameters that `@RequestMapping` does. Notably, it excludes any
server-side specific parameter types. For details, see the list for
xref:integration/rest-clients.adoc#rest-http-interface-method-parameters[@HttpExchange] and
xref:web/webflux/controller/ann-methods/arguments.adoc[@RequestMapping].
@@ -8,22 +8,23 @@ Spring WebFlux has built-in xref:core/validation/validator.adoc[Validation] supp
xref:core/validation/beanvalidation.adoc[Java Bean Validation].
The validation support works on two levels.
First, method parameters such as
First, resolvers for
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] do perform
validation if annotated with Jakarta's `@Valid` or Spring's `@Validated` annotation, and
raise `MethodArgumentNotValidException` in case of validation errors. If you want to handle
the errors in the controller method instead, you can declare an `Errors` or `BindingResult`
method parameter immediately after the validated parameter.
xref:web/webflux/controller/ann-methods/multipart-forms.adoc[@RequestPart] method
parameters perform validation if the parameter has Jakarta's `@Valid` or Spring's
`@Validated` annotation, and raise `MethodArgumentNotValidException` if necessary.
Alternatively, you can handle the errors in the controller method by adding an
`Errors` or `BindingResult` method parameter immediately after the validated one.
Second, if {bean-validation-site}[Java Bean Validation] is present _AND_ other method
parameters, e.g. `@RequestHeader`, `@RequestParam`, `@PathVariable` have `@Constraint`
annotations, then method validation is applied to all method arguments, raising
`HandlerMethodValidationException` in case of validation errors. You can still declare an
`Errors` or `BindingResult` after an `@Valid` method parameter, and handle validation
errors within the controller method, as long as there are no validation errors on other
method arguments.
Second, if {bean-validation-site}[Java Bean Validation] is present _AND_ any method
parameter has `@Constraint` annotations, then method validation is applied instead,
raising `HandlerMethodValidationException` if necessary. For this case you can still add
an `Errors` or `BindingResult` method parameter to handle validation errors within the
controller method, but if other method arguments have validation errors then
`HandlerMethodValidationException` is raised instead. Method validation can apply
to the return value if the method is annotated with `@Valid` or with `@Constraint`
annotations.
You can configure a `Validator` globally through the
xref:web/webflux/config.adoc#webflux-config-validation[WebMvc config], or locally
@@ -760,6 +760,73 @@ Kotlin::
======
[[webmvc-fn-serving-resources]]
== Serving Resources
WebMvc.fn provides built-in support for serving resources.
NOTE: In addition to the capabilities described below, it is possible to implement even more flexible resource handling thanks to
{spring-framework-api}++/web/servlet/function/RouterFunctions.html#resources(java.util.function.Function)++[`RouterFunctions#resource(java.util.function.Function)`].
[[webmvc-fn-resource]]
=== Redirecting to a resource
It is possible to redirect requests matching a specified predicate to a resource. This can be useful, for example,
for handling redirects in Single Page Applications.
[tabs]
======
Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
ClassPathResource index = new ClassPathResource("static/index.html");
List<String> extensions = Arrays.asList("js", "css", "ico", "png", "jpg", "gif");
RequestPredicate spaPredicate = path("/api/**").or(path("/error")).or(pathExtension(extensions::contains)).negate();
RouterFunction<ServerResponse> redirectToIndex = route()
.resource(spaPredicate, index)
.build();
----
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
----
val redirectToIndex = router {
val index = ClassPathResource("static/index.html")
val extensions = listOf("js", "css", "ico", "png", "jpg", "gif")
val spaPredicate = !(path("/api/**") or path("/error") or
pathExtension(extensions::contains))
resource(spaPredicate, index)
}
----
======
[[webmvc-fn-resources]]
=== Serving resources from a root location
It is also possible to route requests that match a given pattern to resources relative to a given root location.
[tabs]
======
Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
Resource location = new FileSystemResource("public-resources/");
RouterFunction<ServerResponse> resources = RouterFunctions.resources("/resources/**", location);
----
Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
----
val location = FileSystemResource("public-resources/")
val resources = router { resources("/resources/**", location) }
----
======
[[webmvc-fn-running]]
== Running a Server
[.small]#xref:web/webflux-functional.adoc#webflux-fn-running[See equivalent in the Reactive stack]#
@@ -78,8 +78,9 @@ it does the same, but it also compares the computed value against the `If-None-M
request header and, if the two are equal, returns a 304 (NOT_MODIFIED).
This strategy saves network bandwidth but not CPU, as the full response must be computed for each request.
State-changing HTTP methods and other HTTP conditional request headers such as `If-Match` and `If-Unmodified-Since` are outside the scope of this filter.
Other strategies at the controller level can avoid the computation and have a broader support for HTTP conditional requests.
State-changing HTTP methods and other HTTP conditional request headers such as `If-Match` and
`If-Unmodified-Since` are outside the scope of this filter. Other strategies at the controller level
can avoid the computation and have a broader support for HTTP conditional requests.
See xref:web/webmvc/mvc-caching.adoc[HTTP Caching].
This filter has a `writeWeakETag` parameter that configures the filter to write weak ETags
@@ -243,4 +243,9 @@ 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]
_AND_ that is not resolved by any other argument resolver is treated as an `@ModelAttribute`.
_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`
support described above does not allow proper ahead-of-time inference of related data
binding reflection hints. As a consequence, it is recommended to explicitly annotate
method parameters with `@ModelAttribute` for use in a GraalVM native image.
@@ -30,6 +30,12 @@ arguably, most controller methods should be mapped to a specific HTTP method ver
using `@RequestMapping`, which, by default, matches to all HTTP methods.
A `@RequestMapping` is still needed at the class level to express shared mappings.
NOTE: `@RequestMapping` cannot be used in conjunction with other `@RequestMapping`
annotations that are declared on the same element (class, interface, or method). If
multiple `@RequestMapping` annotations are detected on the same element, a warning will
be logged, and only the first mapping will be used. This also applies to composed
`@RequestMapping` annotations such as `@GetMapping`, `@PostMapping`, etc.
The following example has type and method level mappings:
[tabs]
@@ -462,11 +468,6 @@ transparently for request mapping. Controller methods do not need to change.
A response wrapper, applied in `jakarta.servlet.http.HttpServlet`, ensures a `Content-Length`
header is set to the number of bytes written (without actually writing to the response).
`@GetMapping` (and `@RequestMapping(method=HttpMethod.GET)`) are implicitly mapped to
and support HTTP HEAD. An HTTP HEAD request is processed as if it were HTTP GET except
that, instead of writing the body, the number of bytes are counted and the `Content-Length`
header is set.
By default, HTTP OPTIONS is handled by setting the `Allow` response header to the list of HTTP
methods listed in all `@RequestMapping` methods that have matching URL patterns.
@@ -491,8 +492,14 @@ attributes with a narrower, more specific purpose.
`@GetMapping`, `@PostMapping`, `@PutMapping`, `@DeleteMapping`, and `@PatchMapping` are
examples of composed annotations. They are provided because, arguably, most
controller methods should be mapped to a specific HTTP method versus using `@RequestMapping`,
which, by default, matches to all HTTP methods. If you need an example of composed
annotations, look at how those are declared.
which, by default, matches to all HTTP methods. If you need an example of how to implement
a composed annotation, look at how those are declared.
NOTE: `@RequestMapping` cannot be used in conjunction with other `@RequestMapping`
annotations that are declared on the same element (class, interface, or method). If
multiple `@RequestMapping` annotations are detected on the same element, a warning will
be logged, and only the first mapping will be used. This also applies to composed
`@RequestMapping` annotations such as `@GetMapping`, `@PostMapping`, etc.
Spring MVC also supports custom request-mapping attributes with custom request-matching
logic. This is a more advanced option that requires subclassing
@@ -562,10 +569,17 @@ Kotlin::
== `@HttpExchange`
[.small]#xref:web/webflux/controller/ann-requestmapping.adoc#webflux-ann-httpexchange-annotation[See equivalent in the Reactive stack]#
As an alternative to `@RequestMapping`, you can also handle requests with `@HttpExchange`
methods. Such methods are declared on an
xref:integration/rest-clients.adoc#rest-http-interface[HTTP Interface] and can be used as
a client via `HttpServiceProxyFactory` or implemented by a server `@Controller`.
While the main purpose of `@HttpExchange` is to abstract HTTP client code with a
generated proxy, the
xref:integration/rest-clients.adoc#rest-http-interface[HTTP Interface] on which
such annotations are placed is a contract neutral to client vs server use.
In addition to simplifying client code, there are also cases where an HTTP Interface
may be a convenient way for servers to expose their API for client access. This leads
to increased coupling between client and server and is often not a good choice,
especially for public API's, but may be exactly the goal for an internal API.
It is an approach commonly used in Spring Cloud, and it is why `@HttpExchange` is
supported as an alternative to `@RequestMapping` for server side handling in
controller classes.
For example:
@@ -575,16 +589,23 @@ Java::
+
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
----
@RestController
@HttpExchange("/persons")
class PersonController {
interface PersonService {
@GetExchange("/{id}")
Person getPerson(@PathVariable Long id);
@PostExchange
void add(@RequestBody Person person);
}
@RestController
class PersonController implements PersonService {
public Person getPerson(@PathVariable Long id) {
// ...
}
@PostExchange
@ResponseStatus(HttpStatus.CREATED)
public void add(@RequestBody Person person) {
// ...
@@ -596,30 +617,38 @@ Kotlin::
+
[source,kotlin,indent=0,subs="verbatim,quotes",role="secondary"]
----
@RestController
@HttpExchange("/persons")
class PersonController {
interface PersonService {
@GetExchange("/{id}")
fun getPerson(@PathVariable id: Long): Person {
fun getPerson(@PathVariable id: Long): Person
@PostExchange
fun add(@RequestBody person: Person)
}
@RestController
class PersonController : PersonService {
override fun getPerson(@PathVariable id: Long): Person {
// ...
}
@PostExchange
@ResponseStatus(HttpStatus.CREATED)
fun add(@RequestBody person: Person) {
override fun add(@RequestBody person: Person) {
// ...
}
}
----
======
There some differences between `@HttpExchange` and `@RequestMapping` since the
former needs to remain suitable for client and server use. For example, while
`@RequestMapping` can be declared to handle any number of paths and each path can
be a pattern, `@HttpExchange` must be declared with a single, concrete path. There are
also differences in the supported method parameters. Generally, `@HttpExchange` supports
a subset of method parameters that `@RequestMapping` does, excluding any parameters that
are server side only. For details see the list of supported method parameters for
xref:integration/rest-clients.adoc#rest-http-interface-method-parameters[HTTP interface] and for
`@HttpExchange` and `@RequestMapping` have differences.
`@RequestMapping` can map to any number of requests by path patterns, HTTP methods,
and more, while `@HttpExchange` declares a single endpoint with a concrete HTTP method,
path, and content types.
For method parameters and returns values, generally, `@HttpExchange` supports a
subset of the method parameters that `@RequestMapping` does. Notably, it excludes any
server-side specific parameter types. For details, see the list for
xref:integration/rest-clients.adoc#rest-http-interface-method-parameters[@HttpExchange] and
xref:web/webmvc/mvc-controller/ann-methods/arguments.adoc[@RequestMapping].
@@ -8,23 +8,23 @@ Spring MVC has built-in xref:core/validation/validator.adoc[Validation] support
xref:core/validation/beanvalidation.adoc[Java Bean Validation].
The validation support works on two levels.
First, method parameters such as
First, resolvers for
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] do perform
validation if annotated with Jakarta's `@Valid` or Spring's `@Validated` annotation, and
raise `MethodArgumentNotValidException` in case of validation errors. If you want to handle
the errors in the controller method instead, you can declare an `Errors` or `BindingResult`
method parameter immediately after the validated parameter.
xref:web/webmvc/mvc-controller/ann-methods/multipart-forms.adoc[@RequestPart] method
parameters perform validation if the parameter has Jakarta's `@Valid` or Spring's
`@Validated` annotation, and raise `MethodArgumentNotValidException` if necessary.
Alternatively, you can handle the errors in the controller method by adding an
`Errors` or `BindingResult` method parameter immediately after the validated one.
Second, if {bean-validation-site}[Java Bean Validation] is present _AND_ other method
parameters, e.g. `@RequestHeader`, `@RequestParam`, `@PathVariable` have `@Constraint`
annotations, then method validation is applied to all method arguments, raising
`HandlerMethodValidationException` in case of validation errors. You can still declare an
`Errors` or `BindingResult` after an `@Valid` method parameter, and handle validation
errors within the controller method, as long as there are no validation errors on other
method arguments. Method validation is also applied to the return value if the method
is annotated with `@Valid` or has other `@Constraint` annotations.
Second, if {bean-validation-site}[Java Bean Validation] is present _AND_ any method
parameter has `@Constraint` annotations, then method validation is applied instead,
raising `HandlerMethodValidationException` if necessary. For this case you can still add
an `Errors` or `BindingResult` method parameter to handle validation errors within the
controller method, but if other method arguments have validation errors then
`HandlerMethodValidationException` is raised instead. Method validation can apply
to the return value if the method is annotated with `@Valid` or with `@Constraint`
annotations.
You can configure a `Validator` globally through the
xref:web/webmvc/mvc-config/validation.adoc[WebMvc config], or locally through an
@@ -109,4 +109,4 @@ Kotlin::
}
})
----
======
======
@@ -38,7 +38,7 @@ The next example uses server-side configuration to register a custom authenticat
interceptor. Note that an interceptor needs only to authenticate and set
the user header on the CONNECT `Message`. Spring notes and saves the authenticated
user and associate it with subsequent STOMP messages on the same session. The following
example shows how register a custom authentication interceptor:
example shows how to register a custom authentication interceptor:
[source,java,indent=0,subs="verbatim,quotes"]
----
@@ -103,9 +103,9 @@ You can also use the WebSocket transport configuration shown earlier to configur
maximum allowed size for incoming STOMP messages. In theory, a WebSocket
message can be almost unlimited in size. In practice, WebSocket servers impose
limits -- for example, 8K on Tomcat and 64K on Jetty. For this reason, STOMP clients
(such as the JavaScript https://github.com/JSteunou/webstomp-client[webstomp-client]
and others) split larger STOMP messages at 16K boundaries and send them as multiple
WebSocket messages, which requires the server to buffer and re-assemble.
such as https://github.com/stomp-js/stompjs[`stomp-js/stompjs`] and others split larger
STOMP messages at 16K boundaries and send them as multiple WebSocket messages,
which requires the server to buffer and re-assemble.
Spring's STOMP-over-WebSocket support does this ,so applications can configure the
maximum size for STOMP messages irrespective of WebSocket server-specific message
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,7 +24,7 @@ import org.springframework.aot.hint.predicate.RuntimeHintsPredicates;
import static org.assertj.core.api.Assertions.assertThat;
public class SpellCheckServiceTests {
class SpellCheckServiceTests {
// tag::hintspredicates[]
@Test
+34 -34
View File
@@ -7,32 +7,33 @@ javaPlatform {
}
dependencies {
api(platform("com.fasterxml.jackson:jackson-bom:2.15.2"))
api(platform("io.micrometer:micrometer-bom:1.12.0"))
api(platform("io.netty:netty-bom:4.1.101.Final"))
api(platform("com.fasterxml.jackson:jackson-bom:2.15.4"))
api(platform("io.micrometer:micrometer-bom:1.12.4"))
api(platform("io.netty:netty-bom:4.1.107.Final"))
api(platform("io.netty:netty5-bom:5.0.0.Alpha5"))
api(platform("io.projectreactor:reactor-bom:2023.0.0"))
api(platform("io.projectreactor:reactor-bom:2023.0.4"))
api(platform("io.rsocket:rsocket-bom:1.1.3"))
api(platform("org.apache.groovy:groovy-bom:4.0.15"))
api(platform("org.apache.groovy:groovy-bom:4.0.19"))
api(platform("org.apache.logging.log4j:log4j-bom:2.21.1"))
api(platform("org.eclipse.jetty:jetty-bom:12.0.3"))
api(platform("org.eclipse.jetty.ee10:jetty-ee10-bom:12.0.3"))
api(platform("org.assertj:assertj-bom:3.25.3"))
api(platform("org.eclipse.jetty:jetty-bom:12.0.7"))
api(platform("org.eclipse.jetty.ee10:jetty-ee10-bom:12.0.7"))
api(platform("org.jetbrains.kotlinx:kotlinx-coroutines-bom:1.7.3"))
api(platform("org.jetbrains.kotlinx:kotlinx-serialization-bom:1.6.0"))
api(platform("org.junit:junit-bom:5.10.1"))
api(platform("org.mockito:mockito-bom:5.7.0"))
api(platform("org.junit:junit-bom:5.10.2"))
api(platform("org.mockito:mockito-bom:5.11.0"))
constraints {
api("com.fasterxml:aalto-xml:1.3.2")
api("com.fasterxml.woodstox:woodstox-core:6.5.1")
api("com.fasterxml.woodstox:woodstox-core:6.6.1")
api("com.github.ben-manes.caffeine:caffeine:3.1.8")
api("com.github.librepdf:openpdf:1.3.33")
api("com.github.librepdf:openpdf:1.3.42")
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.10.1")
api("com.google.protobuf:protobuf-java-util:3.25.0")
api("com.google.protobuf:protobuf-java-util:3.25.3")
api("com.h2database:h2:2.2.224")
api("com.jayway.jsonpath:json-path:2.8.0")
api("com.jayway.jsonpath:json-path:2.9.0")
api("com.rometools:rome:1.19.0")
api("com.squareup.okhttp3:mockwebserver:3.14.9")
api("com.squareup.okhttp3:okhttp:3.14.9")
@@ -41,11 +42,11 @@ dependencies {
api("com.sun.xml.bind:jaxb-core:3.0.2")
api("com.sun.xml.bind:jaxb-impl:3.0.2")
api("com.sun.xml.bind:jaxb-xjc:3.0.2")
api("com.thoughtworks.qdox:qdox:2.0.3")
api("com.thoughtworks.qdox:qdox:2.1.0")
api("com.thoughtworks.xstream:xstream:1.4.20")
api("commons-io:commons-io:2.15.0")
api("de.bechte.junit:junit-hierarchicalcontextrunner:4.12.2")
api("io.micrometer:context-propagation:1.1.0")
api("io.micrometer:context-propagation:1.1.1")
api("io.mockk:mockk:1.13.4")
api("io.projectreactor.netty:reactor-netty5-http:2.0.0-M3")
api("io.projectreactor.tools:blockhound:1.0.8.RELEASE")
@@ -54,9 +55,9 @@ dependencies {
api("io.r2dbc:r2dbc-spi:1.0.0.RELEASE")
api("io.reactivex.rxjava3:rxjava:3.1.8")
api("io.smallrye.reactive:mutiny:1.10.0")
api("io.undertow:undertow-core:2.3.10.Final")
api("io.undertow:undertow-servlet:2.3.10.Final")
api("io.undertow:undertow-websockets-jsr:2.3.10.Final")
api("io.undertow:undertow-core:2.3.12.Final")
api("io.undertow:undertow-servlet:2.3.12.Final")
api("io.undertow:undertow-websockets-jsr:2.3.12.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")
@@ -99,23 +100,22 @@ dependencies {
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.2.1")
api("org.apache.httpcomponents.core5:httpcore5-reactive:5.2.3")
api("org.apache.poi:poi-ooxml:5.2.4")
api("org.apache.tomcat.embed:tomcat-embed-core:10.1.15")
api("org.apache.tomcat.embed:tomcat-embed-websocket:10.1.15")
api("org.apache.tomcat:tomcat-util:10.1.15")
api("org.apache.tomcat:tomcat-websocket:10.1.15")
api("org.aspectj:aspectjrt:1.9.20.1")
api("org.aspectj:aspectjtools:1.9.20.1")
api("org.aspectj:aspectjweaver:1.9.20.1")
api("org.assertj:assertj-core:3.24.2")
api("org.apache.httpcomponents.client5:httpclient5:5.3.1")
api("org.apache.httpcomponents.core5:httpcore5-reactive:5.2.4")
api("org.apache.poi:poi-ooxml:5.2.5")
api("org.apache.tomcat.embed:tomcat-embed-core:10.1.19")
api("org.apache.tomcat.embed:tomcat-embed-websocket:10.1.19")
api("org.apache.tomcat:tomcat-util:10.1.19")
api("org.apache.tomcat:tomcat-websocket:10.1.19")
api("org.aspectj:aspectjrt:1.9.21.1")
api("org.aspectj:aspectjtools:1.9.21.1")
api("org.aspectj:aspectjweaver:1.9.21.1")
api("org.awaitility:awaitility:4.2.0")
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.eclipse.jetty:jetty-reactive-httpclient:4.0.1")
api("org.eclipse.jetty:jetty-reactive-httpclient:4.0.3")
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")
@@ -130,8 +130,8 @@ dependencies {
api("org.hibernate:hibernate-validator:7.0.5.Final")
api("org.hsqldb:hsqldb:2.7.2")
api("org.javamoney:moneta:1.4.2")
api("org.jruby:jruby:9.4.5.0")
api("org.junit.support:testng-engine:1.0.4")
api("org.jruby:jruby:9.4.6.0")
api("org.junit.support:testng-engine:1.0.5")
api("org.mozilla:rhino:1.7.14")
api("org.ogce:xpp3:1.1.6")
api("org.python:jython-standalone:2.7.3")
@@ -139,8 +139,8 @@ dependencies {
api("org.seleniumhq.selenium:htmlunit-driver:2.70.0")
api("org.seleniumhq.selenium:selenium-java:3.141.59")
api("org.skyscreamer:jsonassert:1.5.1")
api("org.slf4j:slf4j-api:2.0.9")
api("org.testng:testng:7.8.0")
api("org.slf4j:slf4j-api:2.0.12")
api("org.testng:testng:7.9.0")
api("org.webjars:underscorejs:1.8.3")
api("org.webjars:webjars-locator-core:0.55")
api("org.xmlunit:xmlunit-assertj:2.9.1")
+2 -2
View File
@@ -1,10 +1,10 @@
version=6.1.1-SNAPSHOT
version=6.1.5
org.gradle.caching=true
org.gradle.jvmargs=-Xmx2048m
org.gradle.parallel=true
kotlinVersion=1.9.20
kotlinVersion=1.9.22
kotlin.jvm.target.validation.mode=ignore
kotlin.stdlib.default.dependency=false
+3 -2
View File
@@ -8,8 +8,9 @@ apply plugin: 'me.champeau.jmh'
apply from: "$rootDir/gradle/publications.gradle"
dependencies {
jmh 'org.openjdk.jmh:jmh-core:1.36'
jmh 'org.openjdk.jmh:jmh-generator-annprocess:1.36'
jmh 'org.openjdk.jmh:jmh-core:1.37'
jmh 'org.openjdk.jmh:jmh-generator-annprocess:1.37'
jmh 'org.openjdk.jmh:jmh-generator-bytecode:1.37'
jmh 'net.sf.jopt-simple:jopt-simple'
}
Binary file not shown.
+1 -1
View File
@@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
Vendored
+10 -10
View File
@@ -43,11 +43,11 @@ set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
@@ -57,11 +57,11 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -75,7 +75,7 @@ class AopNamespaceHandlerScopeIntegrationTests {
}
@Test
void testRequestScoping() throws Exception {
void testRequestScoping() {
MockHttpServletRequest oldRequest = new MockHttpServletRequest();
MockHttpServletRequest newRequest = new MockHttpServletRequest();
@@ -103,7 +103,7 @@ class AopNamespaceHandlerScopeIntegrationTests {
}
@Test
void testSessionScoping() throws Exception {
void testSessionScoping() {
MockHttpSession oldSession = new MockHttpSession();
MockHttpSession newSession = new MockHttpSession();
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,7 +16,6 @@
package org.springframework.aop.framework.autoproxy;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;
@@ -61,12 +60,12 @@ class AdvisorAutoProxyCreatorIntegrationTests {
/**
* Return a bean factory with attributes and EnterpriseServices configured.
*/
protected BeanFactory getBeanFactory() throws IOException {
protected BeanFactory getBeanFactory() {
return new ClassPathXmlApplicationContext(DEFAULT_CONTEXT, CLASS);
}
@Test
void testDefaultExclusionPrefix() throws Exception {
void testDefaultExclusionPrefix() {
DefaultAdvisorAutoProxyCreator aapc = (DefaultAdvisorAutoProxyCreator) getBeanFactory().getBean(ADVISOR_APC_BEAN_NAME);
assertThat(aapc.getAdvisorBeanNamePrefix()).isEqualTo((ADVISOR_APC_BEAN_NAME + DefaultAdvisorAutoProxyCreator.SEPARATOR));
assertThat(aapc.isUsePrefix()).isFalse();
@@ -76,21 +75,21 @@ class AdvisorAutoProxyCreatorIntegrationTests {
* If no pointcuts match (no attrs) there should be proxying.
*/
@Test
void testNoProxy() throws Exception {
void testNoProxy() {
BeanFactory bf = getBeanFactory();
Object o = bf.getBean("noSetters");
assertThat(AopUtils.isAopProxy(o)).isFalse();
}
@Test
void testTxIsProxied() throws Exception {
void testTxIsProxied() {
BeanFactory bf = getBeanFactory();
ITestBean test = (ITestBean) bf.getBean("test");
assertThat(AopUtils.isAopProxy(test)).isTrue();
}
@Test
void testRegexpApplied() throws Exception {
void testRegexpApplied() {
BeanFactory bf = getBeanFactory();
ITestBean test = (ITestBean) bf.getBean("test");
MethodCounter counter = (MethodCounter) bf.getBean("countingAdvice");
@@ -100,7 +99,7 @@ class AdvisorAutoProxyCreatorIntegrationTests {
}
@Test
void testTransactionAttributeOnMethod() throws Exception {
void testTransactionAttributeOnMethod() {
BeanFactory bf = getBeanFactory();
ITestBean test = (ITestBean) bf.getBean("test");
@@ -166,7 +165,7 @@ class AdvisorAutoProxyCreatorIntegrationTests {
}
@Test
void testProgrammaticRollback() throws Exception {
void testProgrammaticRollback() {
BeanFactory bf = getBeanFactory();
Object bean = bf.getBean(TXMANAGER_BEAN_NAME);
@@ -250,7 +249,7 @@ class OrderedTxCheckAdvisor extends StaticMethodMatcherPointcutAdvisor implement
}
@Override
public void afterPropertiesSet() throws Exception {
public void afterPropertiesSet() {
setAdvice(new TxCountingBeforeAdvice());
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -46,7 +46,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Brian Clozel
*/
@EnabledIfRuntimeHintsAgent
public class RuntimeHintsAgentTests {
class RuntimeHintsAgentTests {
private static final ClassLoader classLoader = ClassLoader.getSystemClassLoader();
@@ -58,7 +58,7 @@ public class RuntimeHintsAgentTests {
@BeforeAll
public static void classSetup() throws NoSuchMethodException {
static void classSetup() throws NoSuchMethodException {
defaultConstructor = String.class.getConstructor();
toStringMethod = String.class.getMethod("toString");
privateGreetMethod = PrivateClass.class.getDeclaredMethod("greet");
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -39,7 +39,7 @@ class ComponentBeanDefinitionParserTests {
@BeforeAll
void setUp() throws Exception {
void setUp() {
new XmlBeanDefinitionReader(bf).loadBeanDefinitions(
new ClassPathResource("component-config.xml", ComponentBeanDefinitionParserTests.class));
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -34,7 +34,7 @@ public class ComponentFactoryBean implements FactoryBean<Component> {
}
@Override
public Component getObject() throws Exception {
public Component getObject() {
if (this.children != null && this.children.size() > 0) {
for (Component child : children) {
this.parent.addComponent(child);
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -42,7 +42,6 @@ import static org.assertj.core.api.Assertions.assertThatException;
* @author Chris Beams
* @since 3.1
*/
@SuppressWarnings("resource")
class EnableCachingIntegrationTests {
@Test
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -87,7 +87,6 @@ import static org.springframework.core.env.EnvironmentSystemIntegrationTests.Con
* @author Sam Brannen
* @see org.springframework.context.support.EnvironmentIntegrationTests
*/
@SuppressWarnings("resource")
public class EnvironmentSystemIntegrationTests {
private final ConfigurableEnvironment prodEnv = new StandardEnvironment();
@@ -618,7 +617,7 @@ public class EnvironmentSystemIntegrationTests {
@Import({DevConfig.class, ProdConfig.class})
static class Config {
@Bean
public EnvironmentAwareBean envAwareBean() {
EnvironmentAwareBean envAwareBean() {
return new EnvironmentAwareBean();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2012 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,6 +27,7 @@ import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.expression.TypeConverter;
import org.springframework.util.ClassUtils;
/**
* Copied from Spring Integration for purposes of reproducing
@@ -59,11 +60,9 @@ class BeanFactoryTypeConverter implements TypeConverter, BeanFactoryAware {
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
if (beanFactory instanceof ConfigurableBeanFactory) {
Object typeConverter = ((ConfigurableBeanFactory) beanFactory).getTypeConverter();
if (typeConverter instanceof SimpleTypeConverter) {
delegate = (SimpleTypeConverter) typeConverter;
}
if (beanFactory instanceof ConfigurableBeanFactory cbf &&
cbf.getTypeConverter() instanceof SimpleTypeConverter simpleTypeConverter) {
this.delegate = simpleTypeConverter;
}
}
@@ -86,7 +85,6 @@ class BeanFactoryTypeConverter implements TypeConverter, BeanFactoryAware {
if (conversionService.canConvert(sourceTypeDescriptor, targetTypeDescriptor)) {
return true;
}
// TODO: what does this mean? This method is not used in SpEL so probably ignorable?
Class<?> sourceType = sourceTypeDescriptor.getObjectType();
Class<?> targetType = targetTypeDescriptor.getObjectType();
return canConvert(sourceType, targetType);
@@ -94,7 +92,7 @@ class BeanFactoryTypeConverter implements TypeConverter, BeanFactoryAware {
@Override
public Object convertValue(Object value, TypeDescriptor sourceType, TypeDescriptor targetType) {
if (targetType.getType() == Void.class || targetType.getType() == Void.TYPE) {
if (ClassUtils.isVoidType(targetType.getType())) {
return null;
}
if (conversionService.canConvert(sourceType, targetType)) {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2023 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -51,7 +51,6 @@ import static org.springframework.core.testfixture.TestGroup.LONG_RUNNING;
* @author Juergen Hoeller
* @since 3.1
*/
@SuppressWarnings("resource")
@EnabledForTestGroups(LONG_RUNNING)
class ScheduledAndTransactionalAnnotationIntegrationTests {
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2022 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -54,7 +54,6 @@ import static org.assertj.core.api.Assertions.assertThatException;
* @author Sam Brannen
* @since 3.1
*/
@SuppressWarnings("resource")
class EnableTransactionManagementIntegrationTests {
@Test
@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,14 +27,13 @@ import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests proving that regardless the proxy strategy used (JDK interface-based vs. CGLIB
* subclass-based), discovery of advice-oriented annotations is consistent.
*
* <p>
* For example, Spring's @Transactional may be declared at the interface or class level,
* and whether interface or subclass proxies are used, the @Transactional annotation must
* be discovered in a consistent fashion.
*
* @author Chris Beams
*/
@SuppressWarnings("resource")
class ProxyAnnotationDiscoveryTests {
@Test

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