- 
                Notifications
    You must be signed in to change notification settings 
- Fork 38.8k
What's New in Spring Framework 6.x
        Juergen Hoeller edited this page Jun 10, 2024 
        ·
        157 revisions
      
    - Lenient locking in the core container; see 23501.
- Callback for singleton availability; see 21362.
- Callback for bean factory initialization before singleton pre-instantiation; see 32836.
- Revised lifecycle phases and default timeouts; see 32152.
- Configurable timeouts for individual shutdown phases; see 32985.
- 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 @Qualifiervalue) 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 @Fallbackas companion of@Primary; see 26241.
- Bean definitions with qualifier enforcement, based on defaultCandidate=falseflag; see 26528.
- Support for escaping prefix and separator in property placeholders; see 9628.
- Consistent TaskDecoratorsupport amongTaskSchedulervariants; see 23755.
- Consistent ErrorHandlersupport amongTaskSchedulervariants; see 32460.
- Fully revised documentation for SpEL's property navigation and indexing support.
- Official documentation for indexing into strings and objects in SpEL expressions.
- First-class support for indexing into custom structures via new IndexAccessorandCompilableIndexAccessorSPIs plus a built-inReflectiveIndexAccessorimplementation of those SPIs; see related documentation.
- Safe navigation support for indexing into arrays, collections, strings, maps, objects, and custom structures; see related documentation.
- Improved compilation support for constructor and method invocations that use varargs as well as for expressions that index into arrays and lists with an Integer.
- Methods are now invoked via a public interface or public superclass whenever possible when compiling SpEL expressions.
- Class names generated by the SpEL compiler now take the form org.springframework.expression.spel.generated.CompiledExpression#####, where#####is a 0-padded counter.
- Configurable default rollback rules, including rollbackOnattribute in@EnableTransactionManagement; see 23473.
- Type-level @Qualifierannotations as a hint for default transaction manager selection; see 24291.
- Savepoint callbacks on TransactionSynchronization; see 30509.
- Initial support for JPA 3.2; see 31157.
- Support for backticks for quoted SQL identifiers; see 31944 and 32285.
- Configuration of connection URL via EmbeddedDatabaseBuilder; see 21160.
- Interception of RFC-7807 responses; see 31822.
- Web support for YAML via Jackson; see 32345.
- Efficient webjars version resolution via webjars-locator-lite; see 27619.
- Optimized request predicate execution for router functions; see 32245.
- New URL parser implementation for UriComponentsBuilderetc.; see 32513.
- Support for content negotiation and view rendering in ResponseEntityExceptionHandler; see 31936 and reference documentation.
- 
FormHttpMessageConverternow supports single-value maps; see 32826.
- First-class virtual thread support for JMS DefaultMessageListenerContainer; see 32252.
- JMS DefaultMessageListenerContainerscales up as well as down with its default executor, based on revisedidleReceivesPerTaskLimitsemantics; see 32260.
- First-class mechanism for bean overriding in tests through @TestBean,@MockitoBean, and@MockitoSpyBean; see related documentation.
- Dynamic properties can now be registered from within a test's ApplicationContext; see related documentation.- The DynamicPropertyRegistryis now registered as a singleton bean in a test'sApplicationContextwhich allows it to be injected into@Configurationclasses and@Beanmethods.
- 
@DynamicPropertySourcecan now optionally be applied to a@Beanmethod to signal that the corresponding bean should be eagerly initialized.
 
- The 
- 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.x/4.x support for MockMvc; see 30392.
- Improved JSONPath support; see 31651 and 31653.
- Testing support for WebMvc.fn; see 30477.
- 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=onRefreshoption.
- Lifecycle integrated pause/resume capability and parallel graceful shutdown for ThreadPoolTaskExecutorandThreadPoolTaskScheduleras well asSimpleAsyncTaskScheduler.
- A -Dspring.context.exit=onRefreshoption 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.
- New ModuleResource:Resourceimplementation forjava.lang.Moduleresolution, performinggetInputStream()access viaModule.getResourceAsStream.
- Custom @Componentstereotype annotations may now use@AliasForto configure an annotation attribute override for the component's name. Consequently, the name of the annotation attribute that is used to specify the bean name is no longer required to bevalue, and custom stereotype annotations can now declare an attribute with a different name (such asname) and annotate that attribute with@AliasFor(annotation = Component.class, attribute = "value").
- Convention-based @Componentstereotype names based on thevalueattribute are now deprecated in favor of explicit@AliasFordeclarations. See previous bullet point.
- Spring now finds all @ComponentScanand@PropertySourceannotations; see 30941.
- Async/reactive destroy methods – for example, on R2DBC ConnectionFactory; see 26691.
- Async/reactive cacheable methods, including corresponding support in the Cacheinterface and inCaffeineCacheManager; see 17559 and 17920.
- Reactive @Scheduledmethods (including Kotlin coroutines); see 22924.
- Selecting a specific target scheduler for each @Scheduledmethod; see 20818.
- 
@Scheduledmethods for one-time tasks (with just an initial delay); see 31211.
- Observation instrumentation of @Scheduledmethods; see 29883.
- Spring Framework will not produce observations out-of-the-box for @Asyncor@EventListenerannotated 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 newContextPropagatingTaskDecorator, the relevant reference documentation section, and issue 31130.
- 
Validatorfactory methods for programmatic validator implementations; see 29890.
- 
Validator.validateObject(Object)with returnedErrorsandErrors.failOnErrormethod for flexible programmatic usage; see 19877.
- 
MethodValidationInterceptorthrowsMethodValidationExceptionsubclass ofConstraintViolationExceptionwith violations adapted toMessageSourceresolvable codes, and toErrorsinstances for@Validarguments with cascaded violations; see 29825 and umbrella issue 30645.
- Support for resource patterns in @PropertySource; see 21325.
- Support for IterableandMultiValueMapbinding inBeanWrapperandDirectFieldAccessor; see 907 and 26297.
- Revised InstantandDurationparsing (aligned with Spring Boot); see 22013.
- Spring AOP now supports Kotlin Coroutines; see 22462.
- 
ControlFlowPointcuthas been revised to make its internals more open to extension by subclasses.
- 
ControlFlowPointcutnow provides built-in pattern matching support for method names, analogous to the pattern matching support inNameMatchMethodPointcut. Users can provide one or more method name patterns when constructing aControlFlowPointcut. Alternatively, subclasses can override one of the new protectedisMatch(...)methods – for example, to support regular expressions instead of simple pattern matching.
- New getMergedRepeatableAnnotationAttributes()method inAnnotatedTypeMetadatathat provides dedicated support for finding merged repeatable annotation attributes with full@AliasForsemantics.
- Numerous improvements to the SpEL Language Reference, including but not limited to:
- Supported letters in variable names
- Limitation regarding minimum values for numeric literals
- Safe navigation support for selection and projection
- Safe navigation semantics within compound expressions
- Official documentation of the power operator, custom overloading operators, betweenoperator, increment and decrement operators, as well as the repeat and character subtraction operators for strings
 
- Numerous bug fixes.
- Improved support for constructor and method invocations that use varargs.
- The maximum length of a SpEL expression used in an ApplicationContextis now configurable via thespring.context.expression.maxLengthSpring property.
- Support for letters other than A-Z in property/field/variable names in SpEL expressions; see 30580.
- Support for registering a MethodHandleas a SpEL function; see related documentation.
- Common TransactionExecutionListenercontract withbeforeBegin/afterBegin,beforeCommit/afterCommitandbeforeRollback/afterRollbackcallbacks triggered by the transaction manager (for thread-bound as well as reactive transactions); see 27479.
- 
@TransactionalEventListenerandTransactionalApplicationListeneralways run in the original thread, independent from an async multicaster setup; see 30244.
- 
@TransactionalEventListenerandTransactionalApplicationListenercan participate in reactive transactions when theApplicationEventgets published with the transaction context as its event source; see 27515.
- A failed CompletableFuturetriggers a rollback for an async transactional method; see 30018.
- 
DataAccessUtilsprovides variousoptionalResultmethods with ajava.util.Optionalreturn type; see 27735.
- The new JdbcClientprovides a unified facade for query/update statements on top ofJdbcTemplateandNamedParameterJdbcTemplate, with flexible parameter options as well as flexible result retrieval options; see 30931.
- 
SimplePropertyRowMapperandSimplePropertySqlParameterSourcestrategies for use withJdbcTemplate/NamedParameterJdbcTemplateas well asJdbcClient, providing flexible constructor/property/field mapping for result objects and named parameter holders; see 26594.
- 
SimpleJdbcInsertnow provides support for quoted identifiers which can be enabled via the newusingQuotedIdentifiers()builder method.
- 
SQLExceptionSubclassTranslatorcan be configured with an overridingcustomTranslator; see 24634.
- The R2DBC DatabaseClientprovidesbindValues(Map)for a pre-composed map of parameter values andbindProperties(Object)for parameter objects based on bean properties or record components; see 27282.
- The R2DBC DatabaseClientprovidesmapValue(Class)for plain database column values andmapProperties(Class)for result objects based on bean properties or record components; see 26021.
- 
BeanPropertyRowMapperandDataClassRowMapperavailable for R2DBC as well; see 30530.
- 
JpaTransactionManagerwithHibernateJpaDialecttranslates Hibernate commit/rollback exceptions toDataAccessExceptionsubclasses wherever possible, e.g. toCannotAcquireLockException, aligned with the exception hierarchy thrown from persistence exception translation for repository operations; see 31274 for the primary motivation.
- Spring MVC and WebFlux now have built-in method validation support for controller method parameters with @Constraintannotations. That means you no longer need@Validatedat the controller class level to enable method validation via an 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 HandlerMethodValidationExceptionraised by the new built-in method validation exposes aVisitorAPI to process validation errors by controller method parameter type, e.g.@RequestParameter,@PathVariable, etc.
- 
MethodValidationInterceptorsupports validation ofMonoandFluxmethod parameters; see issue 20781.
- Spring MVC raises NoHandlerFoundExceptionby default if there is no matching handler orResponseStatusException(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 ProblemDetailtype viaMessageSourceand use of customProblemDetailthrough its builder.
- Spring MVC resets the Servlet response buffer prior to handling an error and rendering an error response.
- 
DataBindernow supports constructor binding where argument values are looked up through aNameResolver(e.g. in the HTTP request parameters map), and those lookups can be customized through an@BindParamannotation. 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
- 
@ControllerAdviceand@RestControllerAdvicecan now specify custom component names via their newnameattributes.
- WebFlux provides an option for blocking execution of controller methods with synchronous signatures on a different Executorsuch as theVirtualThreadTaskExecutor; see Blocking Execution in the reference documentation.
- 
SseEmitternow formats data with newlines according to the SSE format.
- New RestClient, a synchronous HTTP client that offers an API similar toWebClient, but sharing infrastructure with theRestTemplate; see 29552.
- Jetty-based ClientHttpRequestFactoryfor use withRestTemplateandRestClient; see 30564.
- JDK HttpClient-based ClientHttpRequestFactoryfor use withRestTemplateandRestClient; see 30478.
- Reactor Netty-based ClientHttpRequestFactoryfor use withRestTemplateandRestClient; see 30835.
- Improved buffering in various ClientHttpRequestFactoryimplementations; see 30557.
- 
HTTP Interface client with built-in adapters for the new RestClientandRestTemplatein addition to the existing adapter for the reactiveWebClient.
- HTTP Interface client supports MultipartFileas an input method parameter.
- HTTP Interface client supports UriBuilderFactoryas an input method parameter to use instead of the one the underlying client is configured with – for example, if it's necessary to vary thebaseUridynamically.
- The @HttpExchangeannotation 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 ClientHttpRequestFactoryfor use withRestTemplateandRestClientand toClientHttpConnectorfor use withWebClient; see 31280, 31281, and 31180.
- General Coroutines support revision in WebFlux, which includes CoroutineContextpropagation inCoWebFilter,CoroutineContextpropagation incoRouterDSL withfilter, a newcontextfunction incoRouterDSL, support for@ModelAttributewith suspending function in WebFlux, and consistent usage of theMonovariant ofawaitSingle().
- Support for Kotlin parameter default and optional values in HTTP handler methods; see 21139 and 29820.
- STOMP messaging supports a new preserveReceiveOrderconfig option for ordered processing of messages received from a given client. That's in addition to the existingpreservePublishOrderflag for messages published to clients; see the Order of Messages section of the reference docs.
- The @RSocketExchangeannotation 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 selectorheader 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: Spring Framework now produces observations when publishing messages with JmsTemplateand when processing messages withMessageListeneror@JmsListener; see the reference docs section and issue 30335.
- 
ApplicationContextfailure threshold support: avoids repeated attempts to load a failingApplicationContextin the TestContext framework, based on a failure threshold which defaults to 1 but can be configured via a system property; see related documentation.
- 
@SpringJUnitConfigand@SpringJUnitWebConfignow declareloaderattributes that support customContextLoaderconfiguration.
- A ContextCustomizerFactorycan now be registered for a particular test class via the new@ContextCustomizerFactoriesannotation.
- Numerous enhancments for @TestPropertySource:- Support for resource patterns (i.e., wildcards) in locations.
- Multiple inlined properties can be supplied via a single text block.
- Property file encoding can be configured via the new encodingattribute.
- A custom PropertySourceFactorycan be configured via the newfactoryattribute in order to support custom property file formats such as JSON, YAML, etc.
 
- Support for resource patterns (i.e., wildcards) in 
- 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.
 
- When used with JUnit Jupiter, @BeforeTransactionand@AfterTransactionmethods can now make use of parameter injection to have Spring components (such as an@Autowired DataSource) injected directly into the method.
- 
JdbcTestUtilshas new overloaded methods that accept aJdbcClientinstead ofJdbcOperations.
- MockMvc now supports initialization of filters with init parameters and mapping to specific dispatch types.
- 
MockMvcWebTestClientnow supports theRequestPostProcessorhook which can, for example, allow varying user identity across tests; see 31298.
- 
MockRestServiceServersupports the newRestClientin addition to theRestTemplate.
- Support for nullinMockHttpServletResponse.setCharacterEncoding(); see 30341.
- Errors encountered during build-time AOT processing now cause the build to fail immediately. This behavior can be disabled by setting the spring.test.aot.processing.failOnErrorproperty tofalse. See Upgrading to 6.1 for migration details.
- New @DisabledInAotModeannotation that can be used to disable AOT build-time processing of a test'sApplicationContextand to disable an entire test class or a single test method at run time when the test suite is run with AOT optimizations enabled.
- 
@Resourcemay now be used for dependency injection in test classes when running in AOT mode.
- Entire framework codebase based on Java 17 source code level now.
- Migration from javaxtojakartanamespace 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).
- Upgrade to ASM 9.4 and Kotlin 1.7.
- Complete CGLIB fork with support for capturing CGLIB-generated classes.
- Comprehensive foundation for Ahead-Of-Time transformations.
- First-class support for GraalVM native images (see related Spring Boot 3 blog post).
- Basic bean property determination without java.beans.Introspectorby 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.
- 
PathMatchingResourcePatternResolveruses NIO and module path APIs for scanning, enabling support for classpath scanning within a GraalVM native image and within the Java module path, respectively.
- 
DefaultFormattingConversionServicesupports ISO-based defaultjava.timetype parsing.
- 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.
- 
RSocket interface client based on @RSocketExchangeservice 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.
- 
HTTP interface client based on @HttpExchangeservice 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).
- 
PathPatternParserused by default (with the ability to opt intoPathMatcher).
- Removal of outdated Tiles and FreeMarker JSP support.
- New PartEventAPI to stream multipart form uploads (both on client and server).
- New ResponseEntityExceptionHandlerto customize WebFlux exceptions and render RFC 7807 error responses.
- 
Fluxreturn values for non-streaming media types (no longer collected toListbefore written).
- Early support for Reactor Netty 2 based on Netty 5 alpha.
- JDK HttpClientintegrated withWebClient.
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.
- 
RestTemplateandWebClientare 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 FluxandMonoreturn values from controller methods.
- 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 @TestExecutionListenersand instead now rely on registration of default listeners.