On this page
5. New Features and Enhancements in Spring Framework 4.2
Version 4.2 included a number of improvements, as described in the following sections:
- Annotations such as
@Beanget detected and processed on Java 8 default methods as well, allowing for composing a configuration class from interfaces with default@Beanmethods. - Configuration classes may declare
@Importwith regular component classes now, allowing for a mix of imported configuration classes and component classes. - Configuration classes may declare an
@Ordervalue, getting processed in a corresponding order (e.g. for overriding beans by name) even when detected through classpath scanning. @Resourceinjection points support an@Lazydeclaration, analogous to@Autowired, receiving a lazy-initializing proxy for the requested target bean.The application event infrastructure now offers an annotation-based model as well as the ability to publish any arbitrary event.
- Any public method in a managed bean can be annotated with
@EventListenerto consume events. @TransactionalEventListenerprovides transaction-bound event support.
- Any public method in a managed bean can be annotated with
Spring Framework 4.2 introduces first-class support for declaring and looking up aliases for annotation attributes. The new
@AliasForannotation can be used to declare a pair of aliased attributes within a single annotation or to declare an alias from one attribute in a custom composed annotation to an attribute in a meta-annotation.- The following annotations have been retrofitted with
@AliasForsupport in order to provide meaningful aliases for theirvalueattributes:@Cacheable,@CacheEvict,@CachePut,@ComponentScan,@ComponentScan.Filter,@ImportResource,@Scope,@ManagedResource,@Header,@Payload,@SendToUser,@ActiveProfiles,@ContextConfiguration,@Sql,@TestExecutionListeners,@TestPropertySource,@Transactional,@ControllerAdvice,@CookieValue,@CrossOrigin,@MatrixVariable,@RequestHeader,@RequestMapping,@RequestParam,@RequestPart,@ResponseStatus,@SessionAttributes,@ActionMapping,@RenderMapping,@EventListener,@TransactionalEventListener. For example,
@ContextConfigurationfrom thespring-testmodule is now declared as follows:public @interface ContextConfiguration { @AliasFor("locations") String[] value() default {}; @AliasFor("value") String[] locations() default {}; // ... }- Similarly, composed annotations that override attributes from meta-annotations can now use
@AliasForfor fine-grained control over exactly which attributes are overridden within an annotation hierarchy. In fact, it is now possible to declare an alias for thevalueattribute of a meta-annotation. For example, one can now develop a composed annotation with a custom attribute override as follows.
@ContextConfiguration public @interface MyTestConfig { @AliasFor(annotation = ContextConfiguration.class, attribute = "value") String[] xmlFiles(); // ... }- See Spring Annotation Programming Model.
- The following annotations have been retrofitted with
- Numerous improvements to Spring’s search algorithms used for finding meta-annotations. For example, locally declared composed annotations are now favored over inherited annotations.
- Composed annotations that override attributes from meta-annotations can now be discovered on interfaces and on abstract, bridge, & interface methods as well as on classes, standard methods, constructors, and fields.
- Maps representing annotation attributes (and
AnnotationAttributesinstances) can be synthesized (i.e., converted) into an annotation. - The features of field-based data binding (
DirectFieldAccessor) have been aligned with the current property-based data binding (BeanWrapper). In particular, field-based binding now supports navigation for Collections, Arrays, and Maps. DefaultConversionServicenow provides out-of-the-box converters forStream,Charset,Currency, andTimeZone. Such converters can be added individually to any arbitraryConversionServiceas well.DefaultFormattingConversionServicecomes with out-of-the-box support for the value types in JSR-354 Money & Currency (if the 'javax.money' API is present on the classpath): namely,MonetaryAmountandCurrencyUnit. This includes support for applying@NumberFormat.@NumberFormatcan now be used as a meta-annotation.JavaMailSenderImplhas a newtestConnection()method for checking connectivity to the server.ScheduledTaskRegistrarexposes scheduled tasks.- Apache
commons-pool2is now supported for a pooling AOPCommonsPool2TargetSource. - Introduced
StandardScriptFactoryas a JSR-223 based mechanism for scripted beans, exposed through thelang:stdelement in XML. Supports e.g. JavaScript and JRuby. (Note: JRubyScriptFactory andlang:jrubyare deprecated now, in favor of using JSR-223.)
javax.transaction.Transactionalis now supported via AspectJ.SimpleJdbcCallOperationsnow supports named binding.- Full support for Hibernate ORM 5.0: as a JPA provider (automatically adapted) as well as through its native API (covered by the new
org.springframework.orm.hibernate5package). - Embedded databases can now be automatically assigned unique names, and
<jdbc:embedded-database>supports a newdatabase-nameattribute. See "Testing Improvements" below for further details.
- The
autoStartupattribute can be controlled viaJmsListenerContainerFactory. - The type of the reply
Destinationcan now be configured per listener container. - The value of the
@SendToannotation can now use a SpEL expression. - The response destination can be computed at runtime using
JmsResponse @JmsListeneris now a repeatable annotation to declare several JMS containers on the same method (use the newly introduced@JmsListenersif you’re not using Java8 yet).
- HTTP Streaming and Server-Sent Events support, see the section called “HTTP Streaming”.
- Built-in support for CORS including global (MVC Java config and XML namespace) and local (e.g.
@CrossOrigin) configuration. See Chapter 27, CORS Support for details. HTTP caching updates:
- new
CacheControlbuilder; plugged intoResponseEntity,WebContentGenerator,ResourceHttpRequestHandler. - improved ETag/Last-Modified support in
WebRequest.
- new
- Custom mapping annotations, using
@RequestMappingas a meta-annotation. - Public methods in
AbstractHandlerMethodMappingto register and unregister request mappings at runtime. - Protected
createDispatcherServletmethod inAbstractDispatcherServletInitializerto further customize theDispatcherServletinstance to use. HandlerMethodas a method argument on@ExceptionHandlermethods, especially handy in@ControllerAdvicecomponents.java.util.concurrent.CompletableFutureas an@Controllermethod return value type.- Byte-range request support in
HttpHeadersand for serving static resources. @ResponseStatusdetected on nested exceptions.UriTemplateHandlerextension point in theRestTemplate.DefaultUriTemplateHandlerexposesbaseUrlproperty and path segment encoding options.- the extension point can also be used to plug in any URI template library.
- OkHTTP integration with the
RestTemplate. - Custom
baseUrlalternative for methods inMvcUriComponentsBuilder. - Serialization/deserialization exception messages are now logged at WARN level.
- Default JSON prefix has been changed from "{} && " to the safer ")]}', " one.
- New
RequestBodyAdviceextension point and built-in implementation to support Jackson’s@JsonViewon@RequestBodymethod arguments. - When using GSON or Jackson 2.6+, the handler method return type is used to improve serialization of parameterized types like
List<Foo>. - Introduced
ScriptTemplateViewas a JSR-223 based mechanism for scripted web views, with a focus on JavaScript view templating on Nashorn (JDK 8).
Expose presence information about connected users and subscriptions:
- new
SimpUserRegistryexposed as a bean named "userRegistry". - sharing of presence information across cluster of servers (see broker relay config options).
- new
- Resolve user destinations across cluster of servers (see broker relay config options).
StompSubProtocolErrorHandlerextension point to customize and control STOMP ERROR frames to clients.- Global
@MessageExceptionHandlermethods via@ControllerAdvicecomponents. - Heart-beats and a SpEL expression 'selector' header for subscriptions with
SimpleBrokerMessageHandler. - STOMP client for use over TCP and WebSocket; see Section 26.4.15, “STOMP Client”.
@SendToand@SendToUsercan contain destination variable placeholders.- Jackson’s
@JsonViewsupported for return values on@MessageMappingand@SubscribeMappingmethods. ListenableFutureandCompletableFutureas return value types from@MessageMappingand@SubscribeMappingmethods.MarshallingMessageConverterfor XML payloads.
JUnit-based integration tests can now be executed with JUnit rules instead of the
SpringJUnit4ClassRunner. This allows Spring-based integration tests to be run with alternative runners like JUnit’sParameterizedor third-party runners such as theMockitoJUnitRunner.- See the section called “Spring JUnit 4 Rules” for details.
The Spring MVC Test framework now provides first-class support for HtmlUnit, including integration with Selenium’s WebDriver, allowing for page-based web application testing without the need to deploy to a Servlet container.
- See Section 15.6.2, “HtmlUnit Integration” for details.
AopTestUtilsis a new testing utility that allows developers to obtain a reference to the underlying target object hidden behind one or more Spring proxies.- See Section 14.2.1, “General testing utilities” for details.
ReflectionTestUtilsnow supports setting and gettingstaticfields, including constants.- The original ordering of bean definition profiles declared via
@ActiveProfilesis now retained in order to support use cases such as Spring Boot’sConfigFileApplicationListenerwhich loads configuration files based on the names of active profiles. @DirtiesContextsupports newBEFORE_METHOD,BEFORE_CLASS, andBEFORE_EACH_TEST_METHODmodes for closing theApplicationContextbefore a test — for example, if some rogue (i.e., yet to be determined) test within a large test suite has corrupted the original configuration for theApplicationContext.@Commitis a new annotation that may be used as a direct replacement for@Rollback(false).@Rollbackmay now be used to configure class-level default rollback semantics.- Consequently,
@TransactionConfigurationis now deprecated and will be removed in a subsequent release.
- Consequently,
@Sqlnow supports execution of inlined SQL statements via a newstatementsattribute.- The
ContextCachethat is used for cachingApplicationContexts between tests is now a public API with a default implementation that can be replaced for custom caching needs. DefaultTestContext,DefaultBootstrapContext, andDefaultCacheAwareContextLoaderDelegateare now public classes in thesupportsubpackage, allowing for custom extensions.TestContextBootstrappers are now responsible for building theTestContext.- In the Spring MVC Test framework,
MvcResultdetails can now be logged atDEBUGlevel or written to a customOutputStreamorWriter. See the newlog(),print(OutputStream), andprint(Writer)methods inMockMvcResultHandlersfor details. - The JDBC XML namespace supports a new
database-nameattribute in<jdbc:embedded-database>, allowing developers to set unique names for embedded databases –- for example, via a SpEL expression or a property placeholder that is influenced by the current active bean definition profiles. Embedded databases can now be automatically assigned a unique name, allowing common test database configuration to be reused in different
ApplicationContexts within a test suite.- See Section 19.8.6, “Generating unique names for embedded databases” for details.
MockHttpServletRequestandMockHttpServletResponsenow provide better support for date header formatting via thegetDateHeaderandsetDateHeadermethods.