Skip to content

What's New in Spring Framework 6.x

Sébastien Deleuze edited this page Apr 23, 2024 · 132 revisions

What's New in Version 6.2

Core Container

  • Revised lifecycle phases and default timeouts; see 32152.
  • Lenient locking in the core container; see 23501.
  • Callback for singleton availability; see 21362.
  • Faster component scanning for multiple scan operations through local root directory and jar caching; see 21190.
  • Background initialization of specific beans via @Bean(bootstrap=BACKGROUND); see 13410 and 19487.
  • Fast shortcut autowiring when parameter name (or @Qualifier value) matches bean name; see 28122 and 17677.
  • Consistent generic type matching for nested/bounded/unresolvable type variables; see 30079, 22902 and 20727.
  • Fallback bean definitions, with @Fallback as companion of @Primary; see 26241.
  • Bean definitions with qualifier enforcement, based on defaultCandidate=false flag; see 26528.
  • Escaping prefix and separator in property placeholders; see 9628.
  • Consistent TaskDecorator support among TaskScheduler variants; see 23755.
  • Consistent ErrorHandler support among TaskScheduler variants; see 32460.

Data Access and Transactions

  • Configurable default rollback rules, including rollbackOn attribute on @EnableTransactionManagement; see 23473.
  • Type-level @Qualifier annotations as a hint for default transaction manager selection; see 24291.
  • Savepoint callbacks on TransactionSynchronization; see 30509.
  • Initial support for JPA 3.2; see 31157.
  • Backticks for quoted SQL identifiers; see 31944 and 32285.
  • Configuration of connection URL via EmbeddedDatabaseBuilder; see 21160.

Web Applications

  • Interception of RFC-7807 responses; see 31822.
  • Optimized request predicate execution for router functions; see 32245.
  • Web support for YAML via Jackson; see 32345.
  • Efficient webjars version resolution via webjars-locator-lite; see 27619.

Messaging Applications

  • First-class virtual thread support for JMS DefaultMessageListenerContainer; see 32252.
  • JMS DefaultMessageListenerContainer scales up as well as down with its default executor, based on revised idleReceivesPerTaskLimit semantics; see 32260.

Testing

  • First-class mechanism for bean overriding in tests through @TestBean and @Mockito(Spy)Bean; see 29917.
  • Servlet 6.1 support in Spring's Servlet API mocks (while retaining Servlet 6.0 compatibility); see 31159.
  • AssertJ support for MockMvc; see 21178.
  • HtmlUnit 3 support for MockMvc; see 30392.
  • Improved JSONPath support; see 31651 and 31653.

What's New in Version 6.1

Core Container

  • General compatibility with virtual threads and JDK 21 overall.
  • Configuration options for virtual threads: a dedicated VirtualThreadTaskExecutor and a virtual threads mode on SimpleAsyncTaskExecutor, plus an analogous SimpleAsyncTaskScheduler with a new-thread-per-task strategy and a virtual threads mode.
  • Lifecycle integration with Project CRaC for JVM checkpoint restore (see related documentation), including a -Dspring.context.checkpoint=onRefresh option.
  • Lifecycle integrated pause/resume capability and parallel graceful shutdown for ThreadPoolTaskExecutor and ThreadPoolTaskScheduler as well as SimpleAsyncTaskScheduler.
  • A -Dspring.context.exit=onRefresh option is available with AppCDS training runs as the main use-case; see 31595.
  • Reachability metadata contribution improvements, preparing for upcoming GraalVM changes: missing reachability metadata will be soon reported as runtime exceptions for better developer experience. See 31213
  • Async/reactive destroy methods (e.g. on R2DBC ConnectionFactory); see 26691.
  • Async/reactive cacheable methods, including corresponding support in the Cache interface and in CaffeineCacheManager; see 17559 and 17920.
  • Reactive @Scheduled methods (including Kotlin coroutines); see 22924.
  • Selecting a specific target scheduler for each @Scheduled method; see 20818.
  • @Scheduled methods for one-time tasks (with just an initial delay); see 31211.
  • Observation instrumentation of @Scheduled methods; see 29883.
  • Spring Framework will not produce observations out-of-the-box for @Async or @EventListener annotated methods, but will help you with propagating context (e.g. MDC logging with the current trace id) for the execution of those methods. See the new ContextPropagatingTaskDecorator, the relevant reference documentation section and issue 31130.
  • Validator factory methods for programmatic validator implementations; see 29890.
  • Validator.validateObject(Object) with returned Errors and Errors.failOnError method for flexible programmatic usage; see 19877.
  • MethodValidationInterceptor throws MethodValidationException subclass of ConstraintViolationException with violations adapted to MessageSource resolvable codes, and to Errors instances for @Valid arguments with cascaded violations. See 29825, and umbrella issue 30645.
  • Support for resource patterns in @PropertySource; see 21325.
  • Support for Iterable and MultiValueMap binding in BeanWrapper and DirectFieldAccessor; see 907 and 26297.
  • Revised Instant and Duration parsing (aligned with Spring Boot); see 22013.
  • Support for letters other than A-Z in property/field/variable names in SpEL expressions; see 30580.
  • Support for registering a MethodHandle as a SpEL function (see related documentation).
  • Spring AOP now supports Coroutines; see 22462.

Data Access and Transactions

  • Common TransactionExecutionListener contract with before/afterBegin, before/afterCommit and before/afterRollback callbacks triggered by the transaction manager (for thread-bound as well as reactive transactions); see 27479.
  • @TransactionalEventListener and TransactionalApplicationListener always run in the original thread, independent from an async multicaster setup; see 30244.
  • @TransactionalEventListener and TransactionalApplicationListener can participate in reactive transactions when the ApplicationEvent gets published with the transaction context as its event source; see 27515.
  • A failed CompletableFuture triggers a rollback for an async transactional method; see 30018.
  • DataAccessUtils provides various optionalResult methods with a java.util.Optional return type; see 27735.
  • The new JdbcClient provides a unified facade for query/update statements on top of JdbcTemplate and NamedParameterJdbcTemplate, with flexible parameter options as well as flexible result retrieval options; see 30931.
  • SimplePropertyRowMapper and SimplePropertySqlParameterSource strategies for use with JdbcTemplate/NamedParameterJdbcTemplate as well as JdbcClient, providing flexible constructor/property/field mapping for result objects and named parameter holders; see 26594.
  • SQLExceptionSubclassTranslator can be configured with an overriding customTranslator; see 24634.
  • The R2DBC DatabaseClient provides bindValues(Map) for a pre-composed map of parameter values and bindProperties(Object) for parameter objects based on bean properties or record components, see 27282.
  • The R2DBC DatabaseClient provides mapValue(Class) for plain database column values and mapProperties(Class) for result objects based on bean properties or record components; see 26021.
  • BeanPropertyRowMapper and DataClassRowMapper available for R2DBC as well; see 30530.
  • JpaTransactionManager with HibernateJpaDialect translates Hibernate commit/rollback exceptions to DataAccessException subclasses wherever possible, e.g. to CannotAcquireLockException, aligned with the exception hierarchy thrown from persistence exception translation for repository operations. See 31274 for the primary motivation: PostgreSQL serialization failures.

Web Applications

  • Spring MVC and WebFlux now have built-in method validation support for controller method parameters with @Constraint annotations. That means you no longer need @Validated at the controller class level to enable method validation via AOP proxy. Built-in method validation is layered on top of the existing argument validation for model attribute and request body arguments. The two are more tightly integrated and coordinated, e.g. avoiding cases with double validation. See Upgrading to 6.1 for migration details, and umbrella issue 30645 for all related tasks and feedback.
  • Method validation is supported with method parameters that are collections, arrays, or maps of objects.
  • The HandlerMethodValidationException raised by the new built-in method validation exposes a Visitor API to process validation errors by controller method parameter type, e.g. @RequestParameter, @PathVariable, etc.
  • MethodValidationInterceptor supports validation of Mono and Flux method parameters, see issue 20781.
  • Spring MVC raises NoHandlerFoundException by default if there is no matching handler, and ResponseStatusException(NOT_FOUND) if there is no matching static resource, and also handles these with the aim of consistent handling for 404 errors out of the box, including RFC 7807 responses. See 29491.
  • ErrorResponse allows customization of ProblemDetail type via MessageSource and use of custom ProblemDetail through its builder.
  • Spring MVC resets the Servlet response buffer prior to handling error and rendering an error response.
  • DataBinder now supports constructor binding where argument values are looked up through a NameResolver (e.g. in the HTTP request parameters map), and those lookups can be customized through an @BindParam annotation. This also supports nested object structures through the invocation of constructors necessary to initialize constructor parameters. The feature is integrated in the data binding of Spring MVC and WebFlux and provides a safer option for data binding of expected parameters only, see Model Design for more details. Spring MVC and WebFlux now support data binding via constructors, including nested objects constructors
  • WebFlux provides option for blocking execution of controller methods with synchronous signature on a different Executor such as the VirtualThreadTaskExecutor, see Blocking Execution in the reference documentation.
  • SseEmitter now formats data with newlines according to the SSE format.
  • New RestClient, a synchronous HTTP client that offers an API similar to WebClient, but sharing infrastructure with the RestTemplate. See 29552.
  • Jetty-based ClientHttpRequestFactory for use with RestTemplate and RestClient; see 30564.
  • JDK HttpClient-based ClientHttpRequestFactory for use with RestTemplate and RestClient; see 30478.
  • Reactor Netty-based ClientHttpRequestFactory for use with RestTemplate and RestClient; see 30835.
  • Improved buffering in various ClientHttpRequestFactory implementations; see 30557.
  • HTTP Interface client built-in adapters for the new RestClient and RestTemplate in addition to the existing adapter for the reactive WebClient.
  • HTTP Interface client supports MultipartFile as an input method parameter.
  • HTTP Interface client supports UriBuilderFactory as an input method parameter to use instead of the one the underlying is configured with, e.g. if necessary to vary the baseURL dynamically.
  • The @HttpExchange annotation used on HTTP interface methods is now supported for server side handling in Spring MVC and WebFlux as an alternative to @RequestMapping, see @HttpExchange for more details and guidance.
  • JVM checkpoint restore support added to Reactor Netty-based ClientHttpRequestFactory for use with RestTemplate and RestClient and ClientHttpConnector for use with WebClient; see 31280, 31281 and 31180.
  • General Coroutines support revision in WebFlux, which includes CoroutineContext propagation in CoWebFilter, CoroutineContext propagation in coRouter DSL with filter, a new context function in coRouter DSL, Support for @ModelAttribute with suspending function in WebFlux and consistent usage of the Mono variant of awaitSingle().
  • Support Kotlin parameter default and optional values in HTTP handler methods; see 21139 and 29820.

Messaging Applications

  • STOMP messaging supports a new preserveReceiveOrder config option for ordered processing of messages received from a given client. That's in addition to the existing preservePublishOrder flag for messages published to clients. See the Order of Messages section of the reference docs.
  • The @RSocketExchange annotation used on RSocket interface methods is now supported for responder side handling as an alternative to @MessageMapping, see @RSocketExchange for more details and guidance.
  • Interface parameter annotations are detected for messaging handler methods as well (analogous to web handler methods).
  • The SpEL-based selector header support in WebSocket messaging is now disabled by default and must be explicitly enabled. See 30550 and Upgrading to 6.1 for migration details.
  • Observability support for JMS. We now produce observations when publishing messages with JmsTemplate and when processing messages with MessageListener or @JmsListener. See the reference docs section and issue 30335.

Testing

  • ApplicationContext failure threshold support: avoids repeated attempts to load a failing ApplicationContext in the TestContext framework, based on a failure threshold which defaults to 1 but can be configured via a system property (see related documentation).
  • Support for recording asynchronous events with @RecordApplicationEvents. See 30020.
    • Record events from threads other than the main test thread.
    • Assert events from a separate thread – for example with Awaitility.
  • MockMvc now supports initialization of filters with init parameters and mapping to specific dispatch types.
  • MockMvcWebTestClient now supports the RequestPostProcessor hook which can for example allow varying user identity across tests. See 31298.
  • MockRestServiceServer supports the new RestClient in addition to the RestTemplate.
  • Support for null in MockHttpServletResponse.setCharacterEncoding(). See 30341.

What's New in Version 6.0

JDK 17+ and Jakarta EE 9+ Baseline

  • Entire framework codebase based on Java 17 source code level now.
  • Migration from javax to jakarta namespace for Servlet, JPA, etc.
  • Runtime compatibility with Jakarta EE 9 as well as Jakarta EE 10 APIs.
  • Compatible with latest web servers: Tomcat 10.1, Jetty 11, Undertow 2.3.
  • Early compatibility with virtual threads (in preview as of JDK 19).

General Core Revision

Core Container

  • Basic bean property determination without java.beans.Introspector by default.
  • AOT processing support in GenericApplicationContext (refreshForAotProcessing).
  • Bean definition transformation based on pre-resolved constructors and factory methods.
  • Support for early proxy class determination for AOP proxies and configuration classes.
  • PathMatchingResourcePatternResolver uses NIO and module path APIs for scanning, enabling support for classpath scanning within a GraalVM native image and within the Java module path, respectively.
  • DefaultFormattingConversionService supports ISO-based default java.time type parsing.

Data Access and Transactions

  • Support for predetermining JPA managed types (for inclusion in AOT processing).
  • JPA support for Hibernate ORM 6.1 (retaining compatibility with Hibernate ORM 5.6).
  • Upgrade to R2DBC 1.0 (including R2DBC transaction definitions).
  • Aligned data access exception translation between JDBC, R2DBC, JPA and Hibernate.
  • Removal of JCA CCI support.

Spring Messaging

  • RSocket interface client based on @RSocketExchange service interfaces.
  • Early support for Reactor Netty 2 based on Netty 5 alpha.
  • Support for Jakarta WebSocket 2.1 and its standard WebSocket protocol upgrade mechanism.

General Web Revision

  • HTTP interface client based on @HttpExchange service interfaces.
  • Support for RFC 7807 problem details.
  • Unified HTTP status code handling.
  • Support for Jackson 2.14.
  • Alignment with Servlet 6.0 (while retaining runtime compatibility with Servlet 5.0).

Spring MVC

  • PathPatternParser used by default (with the ability to opt into PathMatcher).
  • Removal of outdated Tiles and FreeMarker JSP support.

Spring WebFlux

  • New PartEvent API to stream multipart form uploads (both on client and server).
  • New ResponseEntityExceptionHandler to customize WebFlux exceptions and render RFC 7807 error responses.
  • Flux return values for non-streaming media types (no longer collected to List before written).
  • Early support for Reactor Netty 2 based on Netty 5 alpha.
  • JDK HttpClient integrated with WebClient.

Observability

Direct Observability instrumentation with Micrometer Observation in several parts of the Spring Framework. The spring-web module now requires io.micrometer:micrometer-observation:1.10+ as a compile dependency.

  • RestTemplate and WebClient are instrumented to produce HTTP client request observations.
  • Spring MVC can be instrumented for HTTP server observations using the new org.springframework.web.filter.ServerHttpObservationFilter.
  • Spring WebFlux can be instrumented for HTTP server observations using the new org.springframework.web.filter.reactive.ServerHttpObservationFilter.
  • Integration with Micrometer Context Propagation for Flux and Mono return values from controller methods.

Testing

  • Support for testing AOT-processed application contexts on the JVM or within a GraalVM native image.
  • Integration with HtmlUnit 2.64+ request parameter handling.
  • Servlet mocks (MockHttpServletRequest, MockHttpSession) are based on Servlet API 6.0 now.
  • New MockHttpServletRequestBuilder.setRemoteAddress() method.
  • The four abstract base test classes for JUnit 4 and TestNG no longer declare listeners via @TestExecutionListeners and instead now rely on registration of default listeners.