Modularize asciidoc documentation

The reference documentation is now organized in asciidoc bookparts.
Bookparts sections can be also put in separate files, when their
size and theme are important enough to justify that.

Documentation Layout:
```
index
  |-- overview
  |
  |-- whats-new
  |
  |-- core
  |   |-- core-beans
  |   |-- core-aop
  |-- testing
  |
  |-- data-access
  |
  |-- web
  |   |-- web-mvc
  |   |-- web-view
  |-- integration
  |
  |-- appendix
      |-- appx-spring-tld
      |-- appx-spring-form-tld
```

Supersedes and closes #641

Issue: SPR-12309
This commit is contained in:
Brian Clozel
2015-03-03 11:38:01 +01:00
parent 503956d7c5
commit 0baf228db5
17 changed files with 52669 additions and 52786 deletions

View File

@@ -7,7 +7,10 @@ FileUtils.cp_r('images','build')
guard 'shell' do
watch(/^.*\.adoc$/) {|m|
Asciidoctor.render_file(m[0], :to_dir => "build", :safe => Asciidoctor::SafeMode::UNSAFE, :attributes=> {'idprefix' => '', 'idseparator' => '-', 'copycss' => '', 'icons' => 'font', 'source-highlighter' => 'prettify', 'sectanchors' => '', 'doctype' => 'book','toc2' => '', 'spring-version' => '4.0.0.BUILD-SNAPSHOT', 'revnumber' => '4.0.0.BUILD-SNAPSHOT' })
if m[0] != "index.adoc"
Asciidoctor.render_file(m[0], :to_dir => "build", :safe => Asciidoctor::SafeMode::UNSAFE, :attributes=> {'idprefix' => '', 'idseparator' => '-', 'copycss' => '', 'icons' => 'font', 'source-highlighter' => 'prettify', 'sectanchors' => '', 'doctype' => 'book', 'toc' => 'left', 'toclevels' => '2', 'spring-version' => '4.2.0.BUILD-SNAPSHOT', 'revnumber' => '4.2.0.BUILD-SNAPSHOT' })
end
Asciidoctor.render_file("index.adoc", :to_dir => "build", :safe => Asciidoctor::SafeMode::UNSAFE, :attributes=> {'idprefix' => '', 'idseparator' => '-', 'copycss' => '', 'icons' => 'font', 'source-highlighter' => 'prettify', 'sectanchors' => '', 'doctype' => 'book', 'toc' => 'left', 'toclevels' => '1', 'spring-version' => '4.2.0.BUILD-SNAPSHOT', 'revnumber' => '4.2.0.BUILD-SNAPSHOT' })
}
end

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,450 @@
[[spring-tld]]
= spring.tld
[[spring.tld-intro]]
== Introduction
One of the view technologies you can use with the Spring Framework is Java Server Pages
(JSPs). To help you implement views using Java Server Pages the Spring Framework
provides you with some tags for evaluating errors, setting themes and outputting
internationalized messages.
Please note that the various tags generated by this form tag library are compliant with
the http://www.w3.org/TR/xhtml1/[XHTML-1.0-Strict specification] and attendant
http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_XHTML-1.0-Strict[DTD].
This appendix describes the `spring.tld` tag library.
* <<spring.tld.bind>>
* <<spring.tld.escapeBody>>
* <<spring.tld.hasBindErrors>>
* <<spring.tld.htmlEscape>>
* <<spring.tld.message>>
* <<spring.tld.nestedPath>>
* <<spring.tld.theme>>
* <<spring.tld.transform>>
* <<spring.tld.url>>
* <<spring.tld.eval>>
[[spring.tld.bind]]
== the bind tag
Provides BindStatus object for the given bind path. The HTML escaping flag participates
in a page-wide or application-wide setting (i.e. by HtmlEscapeTag or a
"defaultHtmlEscape" context-param in web.xml).
[[spring.tld.bind.table]]
.Attributes
[cols="1,1,1,3"]
|===
| Attribute| Required?| Runtime Expression?| Description
| htmlEscape
| false
| true
| Set HTML escaping for this tag, as boolean value. Overrides the default HTML escaping
setting for the current page.
| ignoreNestedPath
| false
| true
| Set whether to ignore a nested path, if any. Default is to not ignore.
| path
| true
| true
| The path to the bean or bean property to bind status information for. For instance
account.name, company.address.zipCode or just employee. The status object will
exported to the page scope, specifically for this bean or bean property
|===
[[spring.tld.escapeBody]]
== the escapeBody tag
Escapes its enclosed body content, applying HTML escaping and/or JavaScript escaping.
The HTML escaping flag participates in a page-wide or application-wide setting (i.e. by
HtmlEscapeTag or a "defaultHtmlEscape" context-param in web.xml).
[[spring.tld.escapeBody.table]]
.Attributes
[cols="1,1,1,3"]
|===
| Attribute| Required?| Runtime Expression?| Description
| htmlEscape
| false
| true
| Set HTML escaping for this tag, as boolean value. Overrides the default HTML escaping
setting for the current page.
| javaScriptEscape
| false
| true
| Set JavaScript escaping for this tag, as boolean value. Default is false.
|===
[[spring.tld.hasBindErrors]]
== the hasBindErrors tag
Provides Errors instance in case of bind errors. The HTML escaping flag participates in
a page-wide or application-wide setting (i.e. by HtmlEscapeTag or a "defaultHtmlEscape"
context-param in web.xml).
[[spring.tld.hasBindErrors.table]]
.Attributes
[cols="1,1,1,3"]
|===
| Attribute| Required?| Runtime Expression?| Description
| htmlEscape
| false
| true
| Set HTML escaping for this tag, as boolean value. Overrides the default HTML escaping
setting for the current page.
| name
| true
| true
| The name of the bean in the request, that needs to be inspected for errors. If errors
are available for this bean, they will be bound under the 'errors' key.
|===
[[spring.tld.htmlEscape]]
== the htmlEscape tag
Sets default HTML escape value for the current page. Overrides a "defaultHtmlEscape"
context-param in web.xml, if any.
[[spring.tld.htmlEscape.table]]
.Attributes
[cols="1,1,1,3"]
|===
| Attribute| Required?| Runtime Expression?| Description
| defaultHtmlEscape
| true
| true
| Set the default value for HTML escaping, to be put into the current PageContext.
|===
[[spring.tld.message]]
== the message tag
Retrieves the message with the given code, or text if code isn't resolvable. The HTML
escaping flag participates in a page-wide or application-wide setting (i.e. by
HtmlEscapeTag or a "defaultHtmlEscape" context-param in web.xml).
[[spring.tld.message.table]]
.Attributes
[cols="1,1,1,3"]
|===
| Attribute| Required?| Runtime Expression?| Description
| arguments
| false
| true
| Set optional message arguments for this tag, as a (comma-)delimited String (each
String argument can contain JSP EL), an Object array (used as argument array), or a
single Object (used as single argument).
| argumentSeparator
| false
| true
| The separator character to be used for splitting the arguments string value; defaults
to a 'comma' (',').
| code
| false
| true
| The code (key) to use when looking up the message. If code is not provided, the text
attribute will be used.
| htmlEscape
| false
| true
| Set HTML escaping for this tag, as boolean value. Overrides the default HTML escaping
setting for the current page.
| javaScriptEscape
| false
| true
| Set JavaScript escaping for this tag, as boolean value. Default is false.
| message
| false
| true
| A MessageSourceResolvable argument (direct or through JSP EL). Fits nicely when used
in conjunction with Spring's own validation error classes which all implement the
MessageSourceResolvable interface. For example, this allows you to iterate over all of
the errors in a form, passing each error (using a runtime expression) as the value of
this 'message' attribute, thus effecting the easy display of such error messages.
| scope
| false
| true
| The scope to use when exporting the result to a variable. This attribute is only used
when var is also set. Possible values are page, request, session and application.
| text
| false
| true
| Default text to output when a message for the given code could not be found. If both
text and code are not set, the tag will output null.
| var
| false
| true
| The string to use when binding the result to the page, request, session or application
scope. If not specified, the result gets outputted to the writer (i.e. typically
directly to the JSP).
|===
[[spring.tld.nestedPath]]
== the nestedPath tag
Sets a nested path to be used by the bind tag's path.
[[spring.tld.nestedPath.table]]
.Attributes
[cols="1,1,1,3"]
|===
| Attribute| Required?| Runtime Expression?| Description
| path
| true
| true
| Set the path that this tag should apply. E.g. 'customer' to allow bind paths like
'address.street' rather than 'customer.address.street'.
|===
[[spring.tld.theme]]
== the theme tag
Retrieves the theme message with the given code, or text if code isn't resolvable. The
HTML escaping flag participates in a page-wide or application-wide setting (i.e. by
HtmlEscapeTag or a "defaultHtmlEscape" context-param in web.xml).
[[spring.tld.theme.table]]
.Attributes
[cols="1,1,1,3"]
|===
| Attribute| Required?| Runtime Expression?| Description
| arguments
| false
| true
| Set optional message arguments for this tag, as a (comma-)delimited String (each
String argument can contain JSP EL), an Object array (used as argument array), or a
single Object (used as single argument).
| argumentSeparator
| false
| true
| The separator character to be used for splitting the arguments string value; defaults
to a 'comma' (',').
| code
| false
| true
| The code (key) to use when looking up the message. If code is not provided, the text
attribute will be used.
| htmlEscape
| false
| true
| Set HTML escaping for this tag, as boolean value. Overrides the default HTML escaping
setting for the current page.
| javaScriptEscape
| false
| true
| Set JavaScript escaping for this tag, as boolean value. Default is false.
| message
| false
| true
| A MessageSourceResolvable argument (direct or through JSP EL).
| scope
| false
| true
| The scope to use when exporting the result to a variable. This attribute is only used
when var is also set. Possible values are page, request, session and application.
| text
| false
| true
| Default text to output when a message for the given code could not be found. If both
text and code are not set, the tag will output null.
| var
| false
| true
| The string to use when binding the result to the page, request, session or application
scope. If not specified, the result gets outputted to the writer (i.e. typically
directly to the JSP).
|===
[[spring.tld.transform]]
== the transform tag
Provides transformation of variables to Strings, using an appropriate custom
PropertyEditor from BindTag (can only be used inside BindTag). The HTML escaping flag
participates in a page-wide or application-wide setting (i.e. by HtmlEscapeTag or a
'defaultHtmlEscape' context-param in web.xml).
[[spring.tld.transform.table]]
.Attributes
[cols="1,1,1,3"]
|===
| Attribute| Required?| Runtime Expression?| Description
| htmlEscape
| false
| true
| Set HTML escaping for this tag, as boolean value. Overrides the default HTML escaping
setting for the current page.
| scope
| false
| true
| The scope to use when exported the result to a variable. This attribute is only used
when var is also set. Possible values are page, request, session and application.
| value
| true
| true
| The value to transform. This is the actual object you want to have transformed (for
instance a Date). Using the PropertyEditor that is currently in use by the
'spring:bind' tag.
| var
| false
| true
| The string to use when binding the result to the page, request, session or application
scope. If not specified, the result gets outputted to the writer (i.e. typically
directly to the JSP).
|===
[[spring.tld.url]]
== the url tag
Creates URLs with support for URI template variables, HTML/XML escaping, and Javascript
escaping. Modeled after the JSTL c:url tag with backwards compatibility in mind.
[[spring.tld.url.table]]
.Attributes
[cols="1,1,1,3"]
|===
| Attribute| Required?| Runtime Expression?| Description
| url
| true
| true
| The URL to build. This value can include template {placeholders} that are replaced
with the URL encoded value of the named parameter. Parameters must be defined using
the param tag inside the body of this tag.
| context
| false
| true
| Specifies a remote application context path. The default is the current application
context path.
| var
| false
| true
| The name of the variable to export the URL value to. If not specified the URL is
written as output.
| scope
| false
| true
| The scope for the var. 'application', 'session', 'request' and 'page' scopes are
supported. Defaults to page scope. This attribute has no effect unless the var
attribute is also defined.
| htmlEscape
| false
| true
| Set HTML escaping for this tag, as a boolean value. Overrides the default HTML
escaping setting for the current page.
| javaScriptEscape
| false
| true
| Set JavaScript escaping for this tag, as a boolean value. Default is false.
|===
[[spring.tld.eval]]
== the eval tag
Evaluates a Spring expression (SpEL) and either prints the result or assigns it to a
variable.
[[spring.tld.eval.table]]
[cols="1,1,1,3"]
.Attributes
|===
| Attribute| Required?| Runtime Expression?| Description
| expression
| true
| true
| The expression to evaluate.
| var
| false
| true
| The name of the variable to export the evaluation result to. If not specified the
evaluation result is converted to a String and written as output.
| scope
| false
| true
| The scope for the var. 'application', 'session', 'request' and 'page' scopes are
supported. Defaults to page scope. This attribute has no effect unless the var
attribute is also defined.
| htmlEscape
| false
| true
| Set HTML escaping for this tag, as a boolean value. Overrides the default HTML
escaping setting for the current page.
| javaScriptEscape
| false
| true
| Set JavaScript escaping for this tag, as a boolean value. Default is false.
|===

3550
src/asciidoc/core-aop.adoc Normal file

File diff suppressed because it is too large Load Diff

7911
src/asciidoc/core-beans.adoc Normal file

File diff suppressed because it is too large Load Diff

5746
src/asciidoc/core.adoc Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
<productname>Spring Framework</productname>
<releaseinfo>{revnumber}</releaseinfo>
<copyright>
<year>2004-2014</year>
<year>2004-2015</year>
</copyright>
<legalnotice>
<para>Copies of this document may be made for your own use and for distribution to

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

849
src/asciidoc/overview.adoc Normal file
View File

@@ -0,0 +1,849 @@
[[spring-introduction]]
= Overview of Spring Framework
[partintro]
--
The Spring Framework is a lightweight solution and a potential one-stop-shop for
building your enterprise-ready applications. However, Spring is modular, allowing you to
use only those parts that you need, without having to bring in the rest. You can use the
IoC container, with any web framework on top, but you can also use only the
<<orm-hibernate,Hibernate integration code>> or the <<jdbc-introduction,JDBC abstraction
layer>>. The Spring Framework supports declarative transaction management, remote access
to your logic through RMI or web services, and various options for persisting your data.
It offers a full-featured <<mvc-introduction,MVC framework>>, and enables you to
integrate <<aop-introduction,AOP>> transparently into your software.
Spring is designed to be non-intrusive, meaning that your domain logic code generally
has no dependencies on the framework itself. In your integration layer (such as the data
access layer), some dependencies on the data access technology and the Spring libraries
will exist. However, it should be easy to isolate these dependencies from the rest of
your code base.
This document is a reference guide to Spring Framework features. If you have any
requests, comments, or questions on this document, please post them on the
https://groups.google.com/forum/#!forum/spring-framework-contrib[user mailing
list]. Questions on the Framework itself should be asked on StackOverflow
(see https://spring.io/questions[]).
--
[[overview-getting-started-with-spring]]
== Getting Started with Spring
This reference guide provides detailed information about the Spring Framework.
It provides comprehensive documentation for all features, as well as some background
about the underlying concepts (such as __"Dependency Injection"__) that Spring has
embraced.
If you are just getting started with Spring, you may want to begin using the Spring Framework
by creating a http://projects.spring.io/spring-boot/[Spring Boot] based application.
Spring Boot provides a quick (and opinionated) way to create a production-ready Spring based
application. It is based on the Spring Framework, favors convention over configuration, and is
designed to get you up and running as quickly as possible.
You can use http://start.spring.io[start.spring.io] to generate a basic project or follow
one of the https://spring.io/guides["Getting Started" guides] like the
https://spring.io/guides/gs/rest-service/[Getting Started Building a RESTful Web Service]
one. As well as being easier to digest, these guides are very __task focused__, and most of
them are based on Spring Boot. They also cover other projects from the Spring portfolio
that you might want to consider when solving a particular problem.
[[overview]]
== Introduction to the Spring Framework
The Spring Framework is a Java platform that provides comprehensive infrastructure support
for developing Java applications. Spring handles the infrastructure so you can focus on
your application.
Spring enables you to build applications from "plain old Java objects" (POJOs) and to
apply enterprise services non-invasively to POJOs. This capability applies to the Java
SE programming model and to full and partial Java EE.
Examples of how you, as an application developer, can benefit from the Spring platform:
* Make a Java method execute in a database transaction without having to deal with
transaction APIs.
* Make a local Java method a remote procedure without having to deal with remote APIs.
* Make a local Java method a management operation without having to deal with JMX APIs.
* Make a local Java method a message handler without having to deal with JMS APIs.
[[overview-dependency-injection]]
=== Dependency Injection and Inversion of Control
A Java application -- a loose term that runs the gamut from constrained, embedded
applications to n-tier, server-side enterprise applications -- typically consists of
objects that collaborate to form the application proper. Thus the objects in an
application have __dependencies__ on each other.
Although the Java platform provides a wealth of application development functionality,
it lacks the means to organize the basic building blocks into a coherent whole, leaving
that task to architects and developers. Although you can use design patterns such
as __Factory__, __Abstract Factory__, __Builder__, __Decorator__, and __Service Locator__
to compose the various classes and object instances that make up an application,
these patterns are simply that: best practices given a name, with a description
of what the pattern does, where to apply it, the problems it addresses, and so forth.
Patterns are formalized best practices that __you must implement yourself__ in your
application.
The Spring Framework __Inversion of Control__ (IoC) component addresses this concern by
providing a formalized means of composing disparate components into a fully working
application ready for use. The Spring Framework codifies formalized design patterns as
first-class objects that you can integrate into your own application(s). Numerous
organizations and institutions use the Spring Framework in this manner to engineer
robust, __maintainable__ applications.
[[background-ioc]]
.Background
****
"__The question is, what aspect of control are [they] inverting?__" Martin Fowler posed
this question about Inversion of Control (IoC)
http://martinfowler.com/articles/injection.html[on his site] in 2004. Fowler suggested
renaming the principle to make it more self-explanatory and came up with __Dependency
Injection__.
****
[[overview-modules]]
=== Modules
The Spring Framework consists of features organized into about 20 modules. These modules
are grouped into Core Container, Data Access/Integration, Web, AOP (Aspect Oriented
Programming), Instrumentation, Messaging, and Test, as shown in the following diagram.
.Overview of the Spring Framework
image::images/spring-overview.png[width=400]
The following sections list the available modules for each feature along with their
artifact names and the topics they cover. Artifact names correlate to _artifact IDs_ used
in <<dependency-management,Dependency Management tools>>.
[[overview-core-container]]
==== Core Container
The <<beans-introduction,__Core Container__>> consists of the `spring-core`,
`spring-beans`, `spring-context`, `spring-context-support`, and `spring-expression`
(Spring Expression Language) modules.
The `spring-core` and `spring-beans` modules <<beans-introduction,provide the fundamental
parts of the framework>>, including the IoC and Dependency Injection features. The
`BeanFactory` is a sophisticated implementation of the factory pattern. It removes the
need for programmatic singletons and allows you to decouple the configuration and
specification of dependencies from your actual program logic.
The <<context-introduction,__Context__>> (`spring-context`) module builds on the solid
base provided by the <<beans-introduction,__Core and Beans__>> modules: it is a means to
access objects in a framework-style manner that is similar to a JNDI registry. The
Context module inherits its features from the Beans module and adds support for
internationalization (using, for example, resource bundles), event propagation, resource
loading, and the transparent creation of contexts by, for example, a Servlet container.
The Context module also supports Java EE features such as EJB, JMX, and basic remoting.
The `ApplicationContext` interface is the focal point of the Context module.
`spring-context-support` provides support for integrating common third-party libraries
into a Spring application context for caching (EhCache, Guava, JCache), mailing
(JavaMail), scheduling (CommonJ, Quartz) and template engines (FreeMarker, JasperReports,
Velocity).
The `spring-expression` module provides a powerful <<expressions,__Expression
Language__>> for querying and manipulating an object graph at runtime. It is an extension
of the unified expression language (unified EL) as specified in the JSP 2.1
specification. The language supports setting and getting property values, property
assignment, method invocation, accessing the content of arrays, collections and indexers,
logical and arithmetic operators, named variables, and retrieval of objects by name from
Spring's IoC container. It also supports list projection and selection as well as common
list aggregations.
[[overview-aop-instrumentation]]
==== AOP and Instrumentation
The `spring-aop` module provides an <<aop-introduction,__AOP__>> Alliance-compliant
aspect-oriented programming implementation allowing you to define, for example,
method interceptors and pointcuts to cleanly decouple code that implements functionality
that should be separated. Using source-level metadata functionality, you can also
incorporate behavioral information into your code, in a manner similar to that of .NET
attributes.
The separate `spring-aspects` module provides integration with AspectJ.
The `spring-instrument` module provides class instrumentation support and classloader
implementations to be used in certain application servers. The `spring-instrument-tomcat`
module contains Spring's instrumentation agent for Tomcat.
[[overview-messaging]]
==== Messaging
Spring Framework 4 includes a `spring-messaging` module with key abstractions from the
_Spring Integration_ project such as `Message`, `MessageChannel`, `MessageHandler`, and
others to serve as a foundation for messaging-based applications. The module also
includes a set of annotations for mapping messages to methods, similar to the Spring MVC
annotation based programming model.
[[overview-data-access]]
==== Data Access/Integration
The __Data Access/Integration__ layer consists of the JDBC, ORM, OXM, JMS, and
Transaction modules.
The `spring-jdbc` module provides a <<jdbc-introduction,JDBC>>-abstraction layer that
removes the need to do tedious JDBC coding and parsing of database-vendor specific error
codes.
The `spring-tx` module supports <<transaction,programmatic and declarative transaction>>
management for classes that implement special interfaces and for __all your POJOs (Plain
Old Java Objects)__.
The `spring-orm` module provides integration layers for popular
<<orm-introduction,object-relational mapping>> APIs, including <<orm-jpa,JPA>>,
<<orm-jdo,JDO>>, and <<orm-hibernate,Hibernate>>. Using the `spring-orm` module you can
use all of these O/R-mapping frameworks in combination with all of the other features
Spring offers, such as the simple declarative transaction management feature mentioned
previously.
The `spring-oxm` module provides an abstraction layer that supports <<oxm,Object/XML
mapping>> implementations such as JAXB, Castor, XMLBeans, JiBX and XStream.
The `spring-jms` module (<<jms,Java Messaging Service>>) contains features for producing and
consuming messages. Since Spring Framework 4.1, it provides integration with the
`spring-messaging` module.
[[overview-web]]
==== Web
The __Web__ layer consists of the `spring-web`, `spring-webmvc`, `spring-websocket`, and
`spring-webmvc-portlet` modules.
The `spring-web` module provides basic web-oriented integration features such as
multipart file upload functionality and the initialization of the IoC container using
Servlet listeners and a web-oriented application context. It also contains an HTTP client
and the web-related parts of Spring's remoting support.
The `spring-webmvc` module (also known as the __Web-Servlet__ module) contains Spring's
model-view-controller (<<mvc-introduction,__MVC__>>) and REST Web Services implementation
for web applications. Spring's MVC framework provides a clean separation between domain
model code and web forms and integrates with all of the other features of the Spring
Framework.
The `spring-webmvc-portlet` module (also known as the __Web-Portlet__ module) provides
the MVC implementation to be used in a Portlet environment and mirrors the functionality
of the `spring-webmvc` module.
[[overview-testing]]
==== Test
The `spring-test` module supports the <<unit-testing,unit testing>> and
<<integration-testing,integration testing>> of Spring components with JUnit or TestNG. It
provides consistent <<testcontext-ctx-management,loading>> of Spring
++ApplicationContext++s and <<testcontext-ctx-management-caching,caching>> of those
contexts. It also provides <<mock-objects,mock objects>> that you can use to test your
code in isolation.
[[overview-usagescenarios]]
=== Usage scenarios
The building blocks described previously make Spring a logical choice in many scenarios,
from embedded applications that run on resource-constrained devices to full-fledged
enterprise applications that use Spring's transaction management functionality and web
framework integration.
.Typical full-fledged Spring web application
image::images/overview-full.png[width=400]
Spring's <<transaction-declarative,declarative transaction management features>> make
the web application fully transactional, just as it would be if you used EJB
container-managed transactions. All your custom business logic can be implemented with
simple POJOs and managed by Spring's IoC container. Additional services include support
for sending email and validation that is independent of the web layer, which lets you
choose where to execute validation rules. Spring's ORM support is integrated with JPA,
Hibernate and and JDO; for example, when using Hibernate, you can continue to use
your existing mapping files and standard Hibernate `SessionFactory` configuration. Form
controllers seamlessly integrate the web-layer with the domain model, removing the need
for `ActionForms` or other classes that transform HTTP parameters to values for your
domain model.
.Spring middle-tier using a third-party web framework
image::images/overview-thirdparty-web.png[width=400]
Sometimes circumstances do not allow you to completely switch to a different framework.
The Spring Framework does __not__ force you to use everything within it; it is not an
__all-or-nothing__ solution. Existing front-ends built with Struts, Tapestry, JSF
or other UI frameworks can be integrated with a Spring-based middle-tier, which allows
you to use Spring transaction features. You simply need to wire up your business logic
using an `ApplicationContext` and use a `WebApplicationContext` to integrate your web
layer.
.Remoting usage scenario
image::images/overview-remoting.png[width=400]
When you need to access existing code through web services, you can use Spring's
`Hessian-`, `Burlap-`, `Rmi-` or `JaxRpcProxyFactory` classes. Enabling remote access to
existing applications is not difficult.
.EJBs - Wrapping existing POJOs
image::images/overview-ejb.png[width=400]
The Spring Framework also provides an <<ejb,access and abstraction layer>> for
Enterprise JavaBeans, enabling you to reuse your existing POJOs and wrap them in
stateless session beans for use in scalable, fail-safe web applications that might need
declarative security.
[[dependency-management]]
==== Dependency Management and Naming Conventions
Dependency management and dependency injection are different things. To get those nice
features of Spring into your application (like dependency injection) you need to
assemble all the libraries needed (jar files) and get them onto your classpath at
runtime, and possibly at compile time. These dependencies are not virtual components
that are injected, but physical resources in a file system (typically). The process of
dependency management involves locating those resources, storing them and adding them to
classpaths. Dependencies can be direct (e.g. my application depends on Spring at
runtime), or indirect (e.g. my application depends on `commons-dbcp` which depends on
`commons-pool`). The indirect dependencies are also known as "transitive" and it is
those dependencies that are hardest to identify and manage.
If you are going to use Spring you need to get a copy of the jar libraries that comprise
the pieces of Spring that you need. To make this easier Spring is packaged as a set of
modules that separate the dependencies as much as possible, so for example if you don't
want to write a web application you don't need the spring-web modules. To refer to
Spring library modules in this guide we use a shorthand naming convention `spring-{asterisk}` or
`spring-{asterisk}.jar,` where `{asterisk}` represents the short name for the module
(e.g. `spring-core`, `spring-webmvc`, `spring-jms`, etc.). The actual jar file name that
you use is normally the module name concatenated with the version number
(e.g. __spring-core-{spring-version}.jar__).
Each release of the Spring Framework will publish artifacts to the following places:
* Maven Central, which is the default repository that Maven queries, and does not
require any special configuration to use. Many of the common libraries that Spring
depends on also are available from Maven Central and a large section of the Spring
community uses Maven for dependency management, so this is convenient for them. The
names of the jars here are in the form `spring-*-<version>.jar` and the Maven groupId
is `org.springframework`.
* In a public Maven repository hosted specifically for Spring. In addition to the final
GA releases, this repository also hosts development snapshots and milestones. The jar
file names are in the same form as Maven Central, so this is a useful place to get
development versions of Spring to use with other libraries deployed in Maven Central.
This repository also contains a bundle distribution zip file that contains all Spring
jars bundled together for easy download.
So the first thing you need to decide is how to manage your dependencies: we generally
recommend the use of an automated system like Maven, Gradle or Ivy, but you can also do
it manually by downloading all the jars yourself.
You will find bellow the list of Spring artifacts. For a more complete description of each
modules, see <<overview-modules>>.
.Spring Framework Artifacts
|===
|GroupId |ArtifactId |Description
|org.springframework
|spring-aop
|Proxy-based AOP support
|org.springframework
|spring-aspects
|AspectJ based aspects
|org.springframework
|spring-beans
|Beans support, including Groovy
|org.springframework
|spring-context
|Application context runtime, including scheduling and remoting abstractions
|org.springframework
|spring-context-support
|Support classes for integrating common third-party libraries into a Spring application context
|org.springframework
|spring-core
|Core utilities, used by many other Spring modules
|org.springframework
|spring-expression
|Spring Expression Language (SpEL)
|org.springframework
|spring-instrument
|Instrumentation agent for JVM bootstrapping
|org.springframework
|spring-instrument-tomcat
|Instrumentation agent for Tomcat
|org.springframework
|spring-jdbc
|JDBC support package, including DataSource setup and JDBC access support
|org.springframework
|spring-jms
|JMS support package, including helper classes to send and receive JMS messages
|org.springframework
|spring-messaging
|Support for messaging architectures and protocols
|org.springframework
|spring-orm
|Object/Relational Mapping, including JPA and Hibernate support
|org.springframework
|spring-oxm
|Object/XML Mapping
|org.springframework
|spring-test
|Support for unit testing and integration testing Spring components
|org.springframework
|spring-tx
|Transaction infrastructure, including DAO support and JCA integration
|org.springframework
|spring-web
|Web support packages, including client and web remoting
|org.springframework
|spring-webmvc
|REST Web Services and model-view-controller implementation for web applications
|org.springframework
|spring-webmvc-portlet
|MVC implementation to be used in a Portlet environment
|org.springframework
|spring-websocket
|WebSocket and SockJS implementations, including STOMP support
|===
[[overview-spring-dependencies]]
===== Spring Dependencies and Depending on Spring
Although Spring provides integration and support for a huge range of enterprise and
other external tools, it intentionally keeps its mandatory dependencies to an absolute
minimum: you shouldn't have to locate and download (even automatically) a large number
of jar libraries in order to use Spring for simple use cases. For basic dependency
injection there is only one mandatory external dependency, and that is for logging (see
below for a more detailed description of logging options).
Next we outline the basic steps needed to configure an application that depends on
Spring, first with Maven and then with Gradle and finally using Ivy. In all cases, if
anything is unclear, refer to the documentation of your dependency management system, or
look at some sample code - Spring itself uses Gradle to manage dependencies when it is
building, and our samples mostly use Gradle or Maven.
[[overview-maven-dependency-management]]
===== Maven Dependency Management
If you are using http://maven.apache.org/[Maven] for dependency management you don't even
need to supply the logging dependency explicitly. For example, to create an application
context and use dependency injection to configure an application, your Maven dependencies
will look like this:
[source,xml,indent=0]
[subs="verbatim,quotes,attributes"]
----
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>{spring-version}</version>
<scope>runtime</scope>
</dependency>
</dependencies>
----
That's it. Note the scope can be declared as runtime if you don't need to compile
against Spring APIs, which is typically the case for basic dependency injection use
cases.
The example above works with the Maven Central repository. To use the Spring Maven
repository (e.g. for milestones or developer snapshots), you need to specify the
repository location in your Maven configuration. For full releases:
[source,xml,indent=0]
[subs="verbatim,quotes"]
----
<repositories>
<repository>
<id>io.spring.repo.maven.release</id>
<url>http://repo.spring.io/release/</url>
<snapshots><enabled>false</enabled></snapshots>
</repository>
</repositories>
----
For milestones:
[source,xml,indent=0]
[subs="verbatim,quotes"]
----
<repositories>
<repository>
<id>io.spring.repo.maven.milestone</id>
<url>http://repo.spring.io/milestone/</url>
<snapshots><enabled>false</enabled></snapshots>
</repository>
</repositories>
----
And for snapshots:
[source,xml,indent=0]
[subs="verbatim,quotes"]
----
<repositories>
<repository>
<id>io.spring.repo.maven.snapshot</id>
<url>http://repo.spring.io/snapshot/</url>
<snapshots><enabled>true</enabled></snapshots>
</repository>
</repositories>
----
[[overview-maven-bom]]
===== Maven "Bill Of Materials" Dependency =====
It is possible to accidentally mix different versions of Spring JARs when using Maven.
For example, you may find that a third-party library, or another Spring project,
pulls in a transitive dependency to an older release. If you forget to explicitly declare
a direct dependency yourself, all sorts of unexpected issues can arise.
To overcome such problems Maven supports the concept of a "bill of materials" (BOM)
dependency. You can import the `spring-framework-bom` in your `dependencyManagement`
section to ensure that all spring dependencies (both direct and transitive) are at
the same version.
[source,xml,indent=0]
[subs="verbatim,quotes,attributes"]
----
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>{spring-version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
----
An added benefit of using the BOM is that you no longer need to specify the `<version>`
attribute when depending on Spring Framework artifacts:
[source,xml,indent=0]
[subs="verbatim,quotes,attributes"]
----
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependencies>
----
[[overview-gradle-dependency-management]]
===== Gradle Dependency Management
To use the Spring repository with the http://www.gradle.org/[Gradle] build system,
include the appropriate URL in the `repositories` section:
[source,groovy,indent=0]
[subs="verbatim,quotes"]
----
repositories {
mavenCentral()
// and optionally...
maven { url "http://repo.spring.io/release" }
}
----
You can change the `repositories` URL from `/release` to `/milestone` or `/snapshot` as
appropriate. Once a repository has been configured, you can declare dependencies in the
usual Gradle way:
[source,groovy,indent=0]
[subs="verbatim,quotes,attributes"]
----
dependencies {
compile("org.springframework:spring-context:{spring-version}")
testCompile("org.springframework:spring-test:{spring-version}")
}
----
[[overview-ivy-dependency-management]]
===== Ivy Dependency Management
If you prefer to use http://ant.apache.org/ivy[Ivy] to manage dependencies then there
are similar configuration options.
To configure Ivy to point to the Spring repository add the following resolver to your
`ivysettings.xml`:
[source,xml,indent=0]
[subs="verbatim,quotes"]
----
<resolvers>
<ibiblio name="io.spring.repo.maven.release"
m2compatible="true"
root="http://repo.spring.io/release/"/>
</resolvers>
----
You can change the `root` URL from `/release/` to `/milestone/` or `/snapshot/` as
appropriate.
Once configured, you can add dependencies in the usual way. For example (in `ivy.xml`):
[source,xml,indent=0]
[subs="verbatim,quotes,attributes"]
----
<dependency org="org.springframework"
name="spring-core" rev="{spring-version}" conf="compile->runtime"/>
----
[[overview-distribution-zip]]
===== Distribution Zip Files
Although using a build system that supports dependency management is the recommended
way to obtain the Spring Framework, it is still possible to download a distribution
zip file.
Distribution zips are published to the Spring Maven Repository (this is just for our
convenience, you don't need Maven or any other build system in order to download them).
To download a distribution zip open a web browser to
http://repo.spring.io/release/org/springframework/spring and select the appropriate
subfolder for the version that you want. Distribution files end `-dist.zip`, for example
+spring-framework-{spring-version}-RELEASE-dist.zip+. Distributions are also published
for http://repo.spring.io/milestone/org/springframework/spring[milestones] and
http://repo.spring.io/snapshot/org/springframework/spring[snapshots].
[[overview-logging]]
==== Logging
Logging is a very important dependency for Spring because __a)__ it is the only mandatory
external dependency, __b)__ everyone likes to see some output from the tools they are
using, and __c)__ Spring integrates with lots of other tools all of which have also made
a choice of logging dependency. One of the goals of an application developer is often to
have unified logging configured in a central place for the whole application, including
all external components. This is more difficult than it might have been since there are so
many choices of logging framework.
The mandatory logging dependency in Spring is the Jakarta Commons Logging API (JCL). We
compile against JCL and we also make JCL `Log` objects visible for classes that extend
the Spring Framework. It's important to users that all versions of Spring use the same
logging library: migration is easy because backwards compatibility is preserved even
with applications that extend Spring. The way we do this is to make one of the modules
in Spring depend explicitly on `commons-logging` (the canonical implementation of JCL),
and then make all the other modules depend on that at compile time. If you are using
Maven for example, and wondering where you picked up the dependency on
`commons-logging`, then it is from Spring and specifically from the central module
called `spring-core`.
The nice thing about `commons-logging` is that you don't need anything else to make your
application work. It has a runtime discovery algorithm that looks for other logging
frameworks in well known places on the classpath and uses one that it thinks is
appropriate (or you can tell it which one if you need to). If nothing else is available
you get pretty nice looking logs just from the JDK (java.util.logging or JUL for short).
You should find that your Spring application works and logs happily to the console out
of the box in most situations, and that's important.
[[overview-not-using-commons-logging]]
===== Not Using Commons Logging
Unfortunately, the runtime discovery algorithm in `commons-logging`, while convenient
for the end-user, is problematic. If we could turn back the clock and start Spring now
as a new project it would use a different logging dependency. The first choice would
probably be the Simple Logging Facade for Java ( http://www.slf4j.org[SLF4J]), which is
also used by a lot of other tools that people use with Spring inside their applications.
There are basically two ways to switch off `commons-logging`:
. Exclude the dependency from the `spring-core` module (as it is the only module that
explicitly depends on `commons-logging`)
. Depend on a special `commons-logging` dependency that replaces the library with
an empty jar (more details can be found in the
http://slf4j.org/faq.html#excludingJCL[SLF4J FAQ])
To exclude commons-logging, add the following to your `dependencyManagement` section:
[source,xml,indent=0]
[subs="verbatim,quotes,attributes"]
----
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>{spring-version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
----
Now this application is probably broken because there is no implementation of the JCL
API on the classpath, so to fix it a new one has to be provided. In the next section we
show you how to provide an alternative implementation of JCL using SLF4J as an example.
[[overview-logging-slf4j]]
===== Using SLF4J
SLF4J is a cleaner dependency and more efficient at runtime than `commons-logging`
because it uses compile-time bindings instead of runtime discovery of the other logging
frameworks it integrates. This also means that you have to be more explicit about what
you want to happen at runtime, and declare it or configure it accordingly. SLF4J
provides bindings to many common logging frameworks, so you can usually choose one that
you already use, and bind to that for configuration and management.
SLF4J provides bindings to many common logging frameworks, including JCL, and it also
does the reverse: bridges between other logging frameworks and itself. So to use SLF4J
with Spring you need to replace the `commons-logging` dependency with the SLF4J-JCL
bridge. Once you have done that then logging calls from within Spring will be translated
into logging calls to the SLF4J API, so if other libraries in your application use that
API, then you have a single place to configure and manage logging.
A common choice might be to bridge Spring to SLF4J, and then provide explicit binding
from SLF4J to Log4J. You need to supply 4 dependencies (and exclude the existing
`commons-logging`): the bridge, the SLF4J API, the binding to Log4J, and the Log4J
implementation itself. In Maven you would do that like this
[source,xml,indent=0]
[subs="verbatim,quotes,attributes"]
----
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>{spring-version}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
</dependencies>
----
That might seem like a lot of dependencies just to get some logging. Well it is, but it
__is__ optional, and it should behave better than the vanilla `commons-logging` with
respect to classloader issues, notably if you are in a strict container like an OSGi
platform. Allegedly there is also a performance benefit because the bindings are at
compile-time not runtime.
A more common choice amongst SLF4J users, which uses fewer steps and generates fewer
dependencies, is to bind directly to http://logback.qos.ch[Logback]. This removes the
extra binding step because Logback implements SLF4J directly, so you only need to depend
on two libraries not four ( `jcl-over-slf4j` and `logback`). If you do that you might
also need to exclude the slf4j-api dependency from other external dependencies (not
Spring), because you only want one version of that API on the classpath.
[[overview-logging-log4j]]
===== Using Log4J
Many people use http://logging.apache.org/log4j[Log4j] as a logging framework for
configuration and management purposes. It's efficient and well-established, and in fact
it's what we use at runtime when we build and test Spring. Spring also provides some
utilities for configuring and initializing Log4j, so it has an optional compile-time
dependency on Log4j in some modules.
To make Log4j work with the default JCL dependency ( `commons-logging`) all you need to
do is put Log4j on the classpath, and provide it with a configuration file (
`log4j.properties` or `log4j.xml` in the root of the classpath). So for Maven users this
is your dependency declaration:
[source,xml,indent=0]
[subs="verbatim,quotes,attributes"]
----
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>{spring-version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
</dependencies>
----
And here's a sample log4j.properties for logging to the console:
[literal]
[subs="verbatim,quotes"]
----
log4j.rootCategory=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %t %c{2}:%L - %m%n
log4j.category.org.springframework.beans.factory=DEBUG
----
[[overview-native-jcl]]
====== Runtime Containers with Native JCL
Many people run their Spring applications in a container that itself provides an
implementation of JCL. IBM Websphere Application Server (WAS) is the archetype. This
often causes problems, and unfortunately there is no silver bullet solution; simply
excluding `commons-logging` from your application is not enough in most situations.
To be clear about this: the problems reported are usually not with JCL per se, or even
with `commons-logging`: rather they are to do with binding `commons-logging` to another
framework (often Log4J). This can fail because `commons-logging` changed the way they do
the runtime discovery in between the older versions (1.0) found in some containers and
the modern versions that most people use now (1.1). Spring does not use any unusual
parts of the JCL API, so nothing breaks there, but as soon as Spring or your application
tries to do any logging you can find that the bindings to Log4J are not working.
In such cases with WAS the easiest thing to do is to invert the class loader hierarchy
(IBM calls it "parent last") so that the application controls the JCL dependency, not
the container. That option isn't always open, but there are plenty of other suggestions
in the public domain for alternative approaches, and your mileage may vary depending on
the exact version and feature set of the container.

4236
src/asciidoc/testing.adoc Normal file

File diff suppressed because it is too large Load Diff

4971
src/asciidoc/web-mvc.adoc Normal file

File diff suppressed because it is too large Load Diff

2408
src/asciidoc/web-view.adoc Normal file

File diff suppressed because it is too large Load Diff

3908
src/asciidoc/web.adoc Normal file

File diff suppressed because it is too large Load Diff

388
src/asciidoc/whats-new.adoc Normal file
View File

@@ -0,0 +1,388 @@
[[spring-whats-new]]
= What's New in Spring Framework 4.x
[[new-in-4.0]]
== New Features and Enhancements in Spring Framework 4.0
The Spring Framework was first released in 2004; since then there have been significant
major revisions: Spring 2.0 provided XML namespaces and AspectJ support; Spring 2.5
embraced annotation-driven configuration; Spring 3.0 introduced a strong Java 5+ foundation
across the framework codebase, and features such as the Java-based `@Configuration` model.
Version 4.0 is the latest major release of the Spring Framework and the first to fully
support Java 8 features. You can still use Spring with older versions of Java, however,
the minimum requirement has now been raised to Java SE 6. We have also taken the
opportunity of a major release to remove many deprecated classes and methods.
A https://github.com/spring-projects/spring-framework/wiki/Migrating-from-earlier-versions-of-the-spring-framework[migration guide for upgrading to Spring 4.0]
is available on the https://github.com/spring-projects/spring-framework/wiki[Spring Framework GitHub Wiki].
=== Improved Getting Started Experience
The new https://spring.io[spring.io] website provides a whole series of
https://spring.io/guides["Getting Started"] guides to help you learn Spring. You
can read more about the guides in the <<overview-getting-started-with-spring>> section
in this document. The new website also provides a comprehensive overview of the many
additional projects that are released under the Spring umbrella.
If you are a Maven user you may also be interested in the helpful
<<overview-maven-bom,bill of materials>> POM file that is now published with each Spring
Framework release.
=== Removed Deprecated Packages and Methods
All deprecated packages, and many deprecated classes and methods have been removed with
version 4.0. If you are upgrading from a previous release of Spring, you should ensure
that you have fixed any deprecated calls that you were making to outdated APIs.
For a complete set of changes, check out the
http://docs.spring.io/spring-framework/docs/3.2.4.RELEASE_to_4.0.0.RELEASE/[API
Differences Report].
Note that optional third-party dependencies have been raised to a 2010/2011 minimum
(i.e. Spring 4 generally only supports versions released in late 2010 or later now):
notably, Hibernate 3.6+, EhCache 2.1+, Quartz 1.8+, Groovy 1.8+, and Joda-Time 2.0+.
As an exception to the rule, Spring 4 requires the recent Hibernate Validator 4.3+,
and support for Jackson has been focused on 2.0+ now (with Jackson 1.8/1.9 support
retained for the time being where Spring 3.2 had it; now just in deprecated form).
=== Java 8 (as well as 6 and 7)
Spring Framework 4.0 provides support for several Java 8 features. You can make use of
__lambda expressions__ and __method references__ with Spring's callback interfaces. There
is first-class support for `java.time` (http://jcp.org/en/jsr/detail?id=310[JSR-310]),
and several existing annotations have been retrofitted as `@Repeatable`. You can also
use Java 8's parameter name discovery (based on the `-parameters` compiler flag) as an
alternative to compiling your code with debug information enabled.
Spring remains compatible with older versions of Java and the JDK: concretely, Java SE 6
(specifically, a minimum level equivalent to JDK 6 update 18, as released in January 2010)
and above are still fully supported. However, for newly started development projects
based on Spring 4, we recommend the use of Java 7 or 8.
=== Java EE 6 and 7
Java EE version 6 or above is now considered the baseline for Spring Framework 4, with
the JPA 2.0 and Servlet 3.0 specifications being of particular relevance. In order to
remain compatible with Google App Engine and older application servers, it is possible
to deploy a Spring 4 application into a Servlet 2.5 environment. However, Servlet 3.0+
is strongly recommended and a prerequisite in Spring's test and mock packages for test
setups in development environments.
[NOTE]
====
If you are a WebSphere 7 user, be sure to install the JPA 2.0 feature pack. On
WebLogic 10.3.4 or higher, install the JPA 2.0 patch that comes with it. This turns
both of those server generations into Spring 4 compatible deployment environments.
====
On a more forward-looking note, Spring Framework 4.0 supports the Java EE 7 level of
applicable specifications now: in particular, JMS 2.0, JTA 1.2, JPA 2.1, Bean Validation
1.1, and JSR-236 Concurrency Utilities. As usual, this support focuses on individual
use of those specifications, e.g. on Tomcat or in standalone environments. However,
it works equally well when a Spring application is deployed to a Java EE 7 server.
Note that Hibernate 4.3 is a JPA 2.1 provider and therefore only supported as of
Spring Framework 4.0. The same applies to Hibernate Validator 5.0 as a Bean Validation
1.1 provider. Neither of the two are officially supported with Spring Framework 3.2.
[[groovy-bean-definition-dsl]]
=== Groovy Bean Definition DSL
Beginning with Spring Framework 4.0, it is possible to define external bean configuration
using a Groovy DSL. This is similar in concept to using XML bean definitions but allows
for a more concise syntax. Using Groovy also allows you to easily embed bean definitions
directly in your bootstrap code. For example:
[source,groovy,indent=0]
[subs="verbatim,quotes"]
----
def reader = new GroovyBeanDefinitionReader(myApplicationContext)
reader.beans {
dataSource(BasicDataSource) {
driverClassName = "org.hsqldb.jdbcDriver"
url = "jdbc:hsqldb:mem:grailsDB"
username = "sa"
password = ""
settings = [mynew:"setting"]
}
sessionFactory(SessionFactory) {
dataSource = dataSource
}
myService(MyService) {
nestedBean = { AnotherBean bean ->
dataSource = dataSource
}
}
}
----
For more information consult the `GroovyBeanDefinitionReader`
{javadoc-baseurl}/org/springframework/beans/factory/groovy/GroovyBeanDefinitionReader.html[javadocs].
=== Core Container Improvements
There have been several general improvements to the core container:
* Spring now treats <<beans-generics-as-qualifiers,__generic types__ as a form of
__qualifier__>> when injecting Beans. For example, if you are using a Spring Data
`Repository` you can now easily inject a specific implementation:
`@Autowired Repository<Customer> customerRepository`.
* If you use Spring's meta-annotation support, you can now develop custom annotations that
<<beans-meta-annotations,expose specific attributes from the source annotation>>.
* Beans can now be __ordered__ when they are <<beans-autowired-annotation,autowired into
lists and arrays>>. Both the `@Order` annotation and `Ordered` interface are
supported.
* The `@Lazy` annotation can now be used on injection points, as well as on `@Bean`
definitions.
* The <<beans-java-bean-description,`@Description` annotation has been introduced>> for
developers using Java-based configuration.
* A generalized model for <<beans-java-conditional,conditionally filtering beans>> has
been added via the `@Conditional` annotation. This is similar to `@Profile` support but
allows for user-defined strategies to be developed programmatically.
* <<aop-pfb-proxy-types,CGLIB-based proxy classes>> no longer require a default
constructor. Support is provided via the http://code.google.com/p/objenesis/[objenesis]
library which is repackaged __inline__ and distributed as part of the Spring Framework.
With this strategy, no constructor at all is being invoked for proxy instances anymore.
* There is managed time zone support across the framework now, e.g. on `LocaleContext`.
=== General Web Improvements
Deployment to Servlet 2.5 servers remains an option, but Spring Framework 4.0 is now
focused primarily on Servlet 3.0+ environments. If you are using the
<<spring-mvc-test-framework,Spring MVC Test Framework>> you
will need to ensure that a Servlet 3.0 compatible JAR is in your __test classpath__.
In addition to the WebSocket support mentioned later, the following general improvements
have been made to Spring's Web modules:
* You can use the <<mvc-ann-restcontroller,new `@RestController` annotation>> with Spring
MVC applications, removing the need to add `@ResponseBody` to each of your
`@RequestMapping` methods.
* The `AsyncRestTemplate` class has been added, <<rest-async-resttemplate,allowing
non-blocking asynchronous support>> when developing REST clients.
* Spring now offers <<mvc-timezone,comprehensive timezone support>> when developing
Spring MVC applications.
=== WebSocket, SockJS, and STOMP Messaging
A new `spring-websocket` module provides comprehensive support for WebSocket-based,
two-way communication between client and server in web applications. It is compatible with
http://jcp.org/en/jsr/detail?id=356[JSR-356], the Java WebSocket API, and in addition
provides SockJS-based fallback options (i.e. WebSocket emulation) for use in browsers
that don't yet support the WebSocket protocol (e.g. Internet Explorer < 10).
A new `spring-messaging` module adds support for STOMP as the WebSocket sub-protocol
to use in applications along with an annotation programming model for routing and
processing STOMP messages from WebSocket clients. As a result an `@Controller`
can now contain both `@RequestMapping` and `@MessageMapping` methods for handling
HTTP requests and messages from WebSocket-connected clients. The new `spring-messaging`
module also contains key abstractions formerly from the
http://projects.spring.io/spring-integration/[Spring Integration] project such as
`Message`, `MessageChannel`, `MessageHandler`, and others to serve as a foundation
for messaging-based applications.
For further details, including a more thorough introduction, see the <<websocket>> section.
=== Testing Improvements
In addition to pruning of deprecated code within the `spring-test` module, Spring
Framework 4.0 introduces several new features for use in unit and integration testing.
* Almost all annotations in the `spring-test` module (e.g., `@ContextConfiguration`,
`@WebAppConfiguration`, `@ContextHierarchy`, `@ActiveProfiles`, etc.) can now be used
as <<integration-testing-annotations-meta,meta-annotations>> to create custom
_composed annotations_ and reduce configuration duplication across a test suite.
* Active bean definition profiles can now be resolved programmatically, simply by
implementing a custom <<testcontext-ctx-management-env-profiles-ActiveProfilesResolver,`ActiveProfilesResolver`>>
and registering it via the `resolver` attribute of `@ActiveProfiles`.
* A new `SocketUtils` class has been introduced in the `spring-core` module
which enables you to scan for free TCP and UDP server ports on localhost. This
functionality is not specific to testing but can prove very useful when writing
integration tests that require the use of sockets, for example tests that start
an in-memory SMTP server, FTP server, Servlet container, etc.
* As of Spring 4.0, the set of mocks in the `org.springframework.mock.web` package is
now based on the Servlet 3.0 API. Furthermore, several of the Servlet API mocks
(e.g., `MockHttpServletRequest`, `MockServletContext`, etc.) have been updated with
minor enhancements and improved configurability.
[[new-in-4.1]]
== New Features and Enhancements in Spring Framework 4.1
=== JMS Improvements
Spring 4.1 introduces a much simpler infrastructure <<jms-annotated,to register JMS
listener endpoints>> by annotating bean methods with
{javadoc-baseurl}/org/springframework/jms/annotation/JmsListener.html[`@JmsListener`].
The XML namespace has been enhanced to support this new style (`jms:annotation-driven`),
and it is also possible to fully configure the infrastructure using Java config
({javadoc-baseurl}/org/springframework/jms/annotation/EnableJms.html[`@EnableJms`],
`JmsListenerContainerFactory`). It is also possible to register listener endpoints
programmatically using
{javadoc-baseurl}/org/springframework/jms/annotation/JmsListenerConfigurer.html[`JmsListenerConfigurer`].
Spring 4.1 also aligns its JMS support to allow you to benefit from the `spring-messaging`
abstraction introduced in 4.0, that is:
* Message listener endpoints can have a more flexible signature and benefit from
standard messaging annotations such as `@Payload`, `@Header`, `@Headers`, and `@SendTo`. It
is also possible to use a standard `Message` in lieu of `javax.jms.Message` as method
argument.
* A new {javadoc-baseurl}/org/springframework/jms/core/JmsMessageOperations.html[`JmsMessageOperations`]
interface is available and permits `JmsTemplate` like operations using the `Message`
abstraction.
Finally, Spring 4.1 provides additional miscellaneous improvements:
* Synchronous request-reply operations support in `JmsTemplate`
* Listener priority can be specified per `<jms:listener/>` element
* Recovery options for the message listener container are configurable using a
{javadoc-baseurl}/org/springframework/util/backoff/BackOff.html[`BackOff`] implementation
* JMS 2.0 shared consumers are supported
=== Caching Improvements
Spring 4.1 supports <<cache-jsr-107,JCache (JSR-107) annotations>> using Spring's
existing cache configuration and infrastructure abstraction; no changes are required
to use the standard annotations.
Spring 4.1 also improves its own caching abstraction significantly:
* Caches can be resolved at runtime using a
<<cache-annotations-cacheable-cache-resolver,`CacheResolver`>>. As a result the
`value` argument defining the cache name(s) to use is no longer mandatory.
* More operation-level customizations: cache resolver, cache manager, key
generator
* A new <<cache-annotations-config,`@CacheConfig` class-level annotation>> allows
common settings to be shared at the class level **without** enabling any cache operation.
* Better exception handling of cached methods using `CacheErrorHandler`
Spring 4.1 also has a breaking change in the `CacheInterface` as a new `putIfAbsent`
method has been added.
=== Web Improvements
* The existing support for resource handling based on the `ResourceHttpRequestHandler`
has been expanded with new abstractions `ResourceResolver`, `ResourceTransformer`,
and `ResourceUrlProvider`. A number of built-in implementations provide support
for versioned resource URLs (for effective HTTP caching), locating gzipped resources,
generating an HTML 5 AppCache manifests, and more. See <<mvc-config-static-resources>>.
* JDK 1.8's `java.util.Optional` is now supported for `@RequestParam`, `@RequestHeader`,
and `@MatrixVariable` controller method arguments.
* `ListenableFuture` is supported as a return value alternative to `DeferredResult`
where an underlying service (or perhaps a call to `AsyncRestTemplate`) already
returns `ListenableFuture`.
* `@ModelAttribute` methods are now invoked in an order that respects inter-dependencies.
See https://jira.spring.io/browse/SPR-6299[SPR-6299].
* Jackson's `@JsonView` is supported directly on `@ResponseBody` and `ResponseEntity`
controller methods for serializing different amounts of detail for the same POJO (e.g.
summary vs. detail page). This is also supported with View-based rendering by
adding the serialization view type as a model attribute under a special key.
See <<mvc-ann-jsonview>> for details.
* JSONP is now supported with Jackson. See <<mvc-ann-jsonp>>.
* A new lifecycle option is available for intercepting `@ResponseBody` and `ResponseEntity`
methods just after the controller method returns and before the response is written.
To take advantage declare an `@ControllerAdvice` bean that implements `ResponseBodyAdvice`.
The built-in support for `@JsonView` and JSONP take advantage of this.
See <<mvc-handlermapping-interceptor>>.
* There are three new `HttpMessageConverter` options:
** Gson -- lighter footprint than Jackson; has already been in use in Spring Android.
** Google Protocol Buffers -- efficient and effective as an inter-service communication
data protocol within an enterprise but can also be exposed as JSON and XML for browsers.
** Jackson based XML serialization is now supported through the
https://github.com/FasterXML/jackson-dataformat-xml[jackson-dataformat-xml] extension.
When using `@EnableWebMvc` or `<mvc:annotation-driven/>`, this is used by default
instead of JAXB2 if `jackson-dataformat-xml` is in the classpath.
* Views such as JSPs can now build links to controllers by referring to controller mappings
by name. A default name is assigned to every `@RequestMapping`. For example `FooController`
with method `handleFoo` is named "FC#handleFoo". The naming strategy is pluggable.
It is also possible to name an `@RequestMapping` explicitly through its name attribute.
A new `mvcUrl` function in the Spring JSP tag library makes this easy to use in JSP pages.
See <<mvc-links-to-controllers-from-views>>.
* `ResponseEntity` provides a builder-style API to guide controller methods
towards the preparation of server-side responses, e.g. `ResponseEntity.ok()`.
* `RequestEntity` is a new type that provides a builder-style API to guide client-side REST
code towards the preparation of HTTP requests.
* MVC Java config and XML namespace:
** View resolvers can now be configured including support for content
negotiation, see <<mvc-config-view-resolvers>>.
** View controllers now have built-in support for redirects and for setting the response
status. An application can use this to configure redirect URLs, render 404 responses
with a view, send "no content" responses, etc.
Some use cases are
https://jira.spring.io/browse/SPR-11543?focusedCommentId=100308&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-100308[listed here].
** Path matching customizations are frequently used and now built-in.
See <<mvc-config-path-matching>>.
* http://groovy-lang.org/docs/groovy-2.3.6/html/documentation/markup-template-engine.html[Groovy markup template]
support (based on Groovy 2.3). See the `GroovyMarkupConfigurer` and respecitve
`ViewResolver` and `View' implementations.
=== WebSocket STOMP Messaging Improvements
* SockJS (Java) client-side support. See `SockJsClient` and classes in same package.
* New application context events `SessionSubscribeEvent` and `SessionUnsubscribeEvent` published
when STOMP clients subscribe and unsubscribe.
* New "websocket" scope. See <<websocket-stomp-websocket-scope>>.
* `@SendToUser` can target only a single session and does not require an authenticated user.
* `@MessageMapping` methods can use dot "." instead of slash "/" as path separator.
See https://jira.spring.io/browse/SPR-11660[SPR-11660].
* STOMP/WebSocket monitoring info collected and logged. See <<websocket-stomp-stats>>.
* Significantly optimized and improved logging that should remain very readable
and compact even at DEBUG level.
* Optimized message creation including support for temporary message mutability
and avoiding automatic message id and timestamp creation. See Javadoc of
`MessageHeaderAccessor`.
* Close STOMP/WebSocket connections that have no activity within 60 seconds after the
WebSocket session is established. See https://jira.spring.io/browse/SPR-11884[SPR-11884].
=== Testing Improvements
* Groovy scripts can now be used to configure the `ApplicationContext` loaded for
integration tests in the TestContext framework.
** See <<testcontext-ctx-management-groovy>> for details.
* Test-managed transactions can now be programmatically started and ended within
transactional test methods via the new `TestTransaction` API.
** See <<testcontext-tx-programmatic-tx-mgt>> for details.
* SQL script execution can now be configured declaratively via the new `@Sql` and
`@SqlConfig` annotations on a per-class or per-method basis.
** See <<testcontext-executing-sql>> for details.
* Test property sources which automatically override system and application property
sources can be configured via the new `@TestPropertySource` annotation.
** See <<testcontext-ctx-management-property-sources>> for details.
* Default ++TestExecutionListener++s can now be automatically discovered.
** See <<testcontext-tel-config-automatic-discovery>> for details.
* Custom ++TestExecutionListener++s can now be automatically merged with the default
listeners.
** See <<testcontext-tel-config-merging>> for details.
* The documentation for transactional testing support in the TestContext framework has
been improved with more thorough explanations and additional examples.
** See <<testcontext-tx>> for details.
* Various improvements to `MockServletContext`, `MockHttpServletRequest`, and other
Servlet API mocks.
* `AssertThrows` has been refactored to support `Throwable` instead of `Exception`.
* In Spring MVC Test, JSON responses can be asserted with https://github.com/skyscreamer/JSONassert[JSON Assert]
as an extra option to using JSONPath much like it has been possible to do for XML with
XMLUnit.
* `MockMvcBuilder` _recipes_ can now be created with the help of `MockMvcConfigurer`. This
was added to make it easy to apply Spring Security setup but can be used to encapsulate
common setup for any 3rd party framework or within a project.
* `MockRestServiceServer` now supports the `AsyncRestTemplate` for client-side testing.