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
@Bean
get detected and processed on Java 8 default methods as well, allowing for composing a configuration class from interfaces with default@Bean
methods. - Configuration classes may declare
@Import
with regular component classes now, allowing for a mix of imported configuration classes and component classes. - Configuration classes may declare an
@Order
value, getting processed in a corresponding order (e.g. for overriding beans by name) even when detected through classpath scanning. @Resource
injection points support an@Lazy
declaration, 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
@EventListener
to consume events. @TransactionalEventListener
provides 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
@AliasFor
annotation 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
@AliasFor
support in order to provide meaningful aliases for theirvalue
attributes:@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,
@ContextConfiguration
from thespring-test
module 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
@AliasFor
for fine-grained control over exactly which attributes are overridden within an annotation hierarchy. In fact, it is now possible to declare an alias for thevalue
attribute 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
AnnotationAttributes
instances) 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. DefaultConversionService
now provides out-of-the-box converters forStream
,Charset
,Currency
, andTimeZone
. Such converters can be added individually to any arbitraryConversionService
as well.DefaultFormattingConversionService
comes 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,MonetaryAmount
andCurrencyUnit
. This includes support for applying@NumberFormat
.@NumberFormat
can now be used as a meta-annotation.JavaMailSenderImpl
has a newtestConnection()
method for checking connectivity to the server.ScheduledTaskRegistrar
exposes scheduled tasks.- Apache
commons-pool2
is now supported for a pooling AOPCommonsPool2TargetSource
. - Introduced
StandardScriptFactory
as a JSR-223 based mechanism for scripted beans, exposed through thelang:std
element in XML. Supports e.g. JavaScript and JRuby. (Note: JRubyScriptFactory andlang:jruby
are deprecated now, in favor of using JSR-223.)
javax.transaction.Transactional
is now supported via AspectJ.SimpleJdbcCallOperations
now 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.hibernate5
package). - Embedded databases can now be automatically assigned unique names, and
<jdbc:embedded-database>
supports a newdatabase-name
attribute. See "Testing Improvements" below for further details.
- The
autoStartup
attribute can be controlled viaJmsListenerContainerFactory
. - The type of the reply
Destination
can now be configured per listener container. - The value of the
@SendTo
annotation can now use a SpEL expression. - The response destination can be computed at runtime using
JmsResponse
@JmsListener
is now a repeatable annotation to declare several JMS containers on the same method (use the newly introduced@JmsListeners
if 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
CacheControl
builder; plugged intoResponseEntity
,WebContentGenerator
,ResourceHttpRequestHandler
. - improved ETag/Last-Modified support in
WebRequest
.
- new
- Custom mapping annotations, using
@RequestMapping
as a meta-annotation. - Public methods in
AbstractHandlerMethodMapping
to register and unregister request mappings at runtime. - Protected
createDispatcherServlet
method inAbstractDispatcherServletInitializer
to further customize theDispatcherServlet
instance to use. HandlerMethod
as a method argument on@ExceptionHandler
methods, especially handy in@ControllerAdvice
components.java.util.concurrent.CompletableFuture
as an@Controller
method return value type.- Byte-range request support in
HttpHeaders
and for serving static resources. @ResponseStatus
detected on nested exceptions.UriTemplateHandler
extension point in theRestTemplate
.DefaultUriTemplateHandler
exposesbaseUrl
property 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
baseUrl
alternative 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
RequestBodyAdvice
extension point and built-in implementation to support Jackson’s@JsonView
on@RequestBody
method 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
ScriptTemplateView
as 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
SimpUserRegistry
exposed 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).
StompSubProtocolErrorHandler
extension point to customize and control STOMP ERROR frames to clients.- Global
@MessageExceptionHandler
methods via@ControllerAdvice
components. - 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”.
@SendTo
and@SendToUser
can contain destination variable placeholders.- Jackson’s
@JsonView
supported for return values on@MessageMapping
and@SubscribeMapping
methods. ListenableFuture
andCompletableFuture
as return value types from@MessageMapping
and@SubscribeMapping
methods.MarshallingMessageConverter
for 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’sParameterized
or 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.
AopTestUtils
is 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.
ReflectionTestUtils
now supports setting and gettingstatic
fields, including constants.- The original ordering of bean definition profiles declared via
@ActiveProfiles
is now retained in order to support use cases such as Spring Boot’sConfigFileApplicationListener
which loads configuration files based on the names of active profiles. @DirtiesContext
supports newBEFORE_METHOD
,BEFORE_CLASS
, andBEFORE_EACH_TEST_METHOD
modes for closing theApplicationContext
before 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
.@Commit
is a new annotation that may be used as a direct replacement for@Rollback(false)
.@Rollback
may now be used to configure class-level default rollback semantics.- Consequently,
@TransactionConfiguration
is now deprecated and will be removed in a subsequent release.
- Consequently,
@Sql
now supports execution of inlined SQL statements via a newstatements
attribute.- The
ContextCache
that is used for cachingApplicationContext
s between tests is now a public API with a default implementation that can be replaced for custom caching needs. DefaultTestContext
,DefaultBootstrapContext
, andDefaultCacheAwareContextLoaderDelegate
are now public classes in thesupport
subpackage, allowing for custom extensions.TestContextBootstrapper
s are now responsible for building theTestContext
.- In the Spring MVC Test framework,
MvcResult
details can now be logged atDEBUG
level or written to a customOutputStream
orWriter
. See the newlog()
,print(OutputStream)
, andprint(Writer)
methods inMockMvcResultHandlers
for details. - The JDBC XML namespace supports a new
database-name
attribute 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
ApplicationContext
s within a test suite.- See Section 19.8.6, “Generating unique names for embedded databases” for details.
MockHttpServletRequest
andMockHttpServletResponse
now provide better support for date header formatting via thegetDateHeader
andsetDateHeader
methods.