Break down Core and Web chapters in reference doc

Core and Web chapters are important chapters in the Spring Framework
reference documentation, and splitting them in multiple files will
help to evolve the documentation while not creating too many files.

Issue: SPR-12309
This commit is contained in:
Brian Clozel 2015-03-06 16:57:32 +01:00
parent ff4ac5b837
commit 74072237ee
15 changed files with 9735 additions and 9731 deletions

View File

@ -1106,7 +1106,7 @@ configure(rootProject) {
asciidoctor {
sourceDir project.file('src/asciidoc')
separateOutputDirs = false
backends = ['docbook5']
backends = ['docbook']
options doctype: 'book', eruby: 'erubis'
attributes 'spring-version': project.version,
revnumber : project.version,

File diff suppressed because it is too large Load Diff

View File

@ -36,11 +36,11 @@ AOP is used in the Spring Framework to...
* ... allow users to implement custom aspects, complementing their use of OOP with AOP.
[NOTE]
===
====
If you are interested only in generic declarative services or other pre-packaged
declarative middleware services such as pooling, you do not need to work directly with
Spring AOP, and can skip most of this chapter.
===
====

View File

@ -92,12 +92,12 @@ which is what most of this chapter uses to convey key concepts and features of t
Spring IoC container.
[NOTE]
===
====
XML-based metadata is __not__ the only allowed form of configuration metadata. The
Spring IoC container itself is __totally__ decoupled from the format in which this
configuration metadata is actually written. These days many developers choose
<<beans-java,Java-based configuration>> for their Spring applications.
===
====
For information about using other forms of metadata with the Spring container, see:
@ -171,13 +171,13 @@ as the local file system, from the Java `CLASSPATH`, and so on.
----
[NOTE]
===
====
After you learn about Spring's IoC container, you may want to know more about Spring's
`Resource` abstraction, as described in <<resources>>, which provides a convenient
mechanism for reading an InputStream from locations defined in a URI syntax. In
particular, `Resource` paths are used to construct applications contexts as described in
<<resources-app-ctx>>.
===
====
The following example shows the service layer objects `(services.xml)` configuration file:
@ -271,7 +271,7 @@ contents of the files being imported, including the top level `<beans/>` element
be valid XML bean definitions according to the Spring Schema.
[NOTE]
===
====
It is possible, but not recommended, to reference files in parent directories using a
relative "../" path. Doing so creates a dependency on a file that is outside the current
application. In particular, this reference is not recommended for "classpath:" URLs (for
@ -285,7 +285,7 @@ aware that you are coupling your application's configuration to specific absolut
locations. It is generally preferable to keep an indirection for such absolute
locations, for example, through "${...}" placeholders that are resolved against JVM
system properties at runtime.
===
====
@ -662,14 +662,14 @@ dependency injection (DI). See <<beans-factory-properties-detailed,Dependencies
configuration in detail>>.
[NOTE]
===
====
In Spring documentation,__ factory bean__ refers to a bean that is configured in the
Spring container that will create objects through an
<<beans-factory-class-instance-factory-method,instance>> or
<<beans-factory-class-static-factory-method,static>> factory method. By contrast,
`FactoryBean` (notice the capitalization) refers to a Spring-specific
<<beans-factory-extension-factorybean, `FactoryBean` >>.
===
====
@ -1276,11 +1276,11 @@ bean is a <<beans-factory-scopes,prototype>> bean, this typo and the resulting e
may only be discovered long after the container is deployed.
[NOTE]
===
====
The `local` attribute on the `idref` element is no longer supported in the 4.0 beans xsd
since it does not provide value over a regular `bean` reference anymore. Simply change
your existing `idref local` references to `idref bean` when upgrading to the 4.0 schema.
===
====
A common place (at least in versions earlier than Spring 2.0) where the `<idref/>` element
brings value is in the configuration of <<aop-pfb-1,AOP interceptors>> in a
@ -1342,11 +1342,11 @@ container with a proxy that will have the same name as the parent bean.
----
[NOTE]
===
====
The `local` attribute on the `ref` element is no longer supported in the 4.0 beans xsd
since it does not provide value over a regular `bean` reference anymore. Simply change
your existing `ref local` references to `ref bean` when upgrading to the 4.0 schema.
===
====
[[beans-inner-beans]]
@ -1659,13 +1659,13 @@ whereas the `-ref` part indicates that this is not a straight value but rather a
reference to another bean.
[NOTE]
===
====
The p-namespace is not as flexible as the standard XML format. For example, the format
for declaring property references clashes with properties that end in `Ref`, whereas the
standard XML format does not. We recommend that you choose your approach carefully and
communicate this to your team members, to avoid producing XML documents that use all
three approaches at the same time.
===
====
[[beans-c-namespace]]
@ -1718,10 +1718,10 @@ argument indexes:
----
[NOTE]
===
====
Due to the XML grammar, the index notation requires the presence of the leading `_` as
XML attribute names cannot start with a number (even though some IDE allow it).
===
====
In practice, the constructor resolution
<<beans-factory-ctor-arguments-resolution,mechanism>> is quite efficient in matching
@ -1785,13 +1785,13 @@ delimiters:
----
[NOTE]
===
====
The `depends-on` attribute in the bean definition can specify both an initialization
time dependency and, in the case of <<beans-factory-scopes-singleton,singleton>> beans
only, a corresponding destroy time dependency. Dependent beans that define a
`depends-on` relationship with a given bean are destroyed first, prior to the given bean
itself being destroyed. Thus `depends-on` can also control shutdown order.
===
====
@ -2031,7 +2031,7 @@ bytecode generation from the CGLIB library to generate dynamically a subclass th
overrides the method.
[NOTE]
===
====
For this dynamic subclassing to work, the class that the Spring container will subclass
cannot be `final`, and the method to be overridden cannot be `final` either. Also,
testing a class that has an `abstract` method requires you to subclass the class
@ -2041,7 +2041,7 @@ is no longer necessary to add CGLIB to your classpath, because CGLIB classes are
repackaged under org.springframework and distributed within the spring-core JAR. This is
done both for convenience as well as to avoid potential conflicts with other projects
that use differing versions of CGLIB.
===
====
Looking at the `CommandManager` class in the previous code snippet, you see that the
Spring container will dynamically override the implementation of the `createCommand()`
@ -2248,13 +2248,13 @@ The following scopes are supported out of the box. You can also create
|===
[NOTE]
===
====
As of Spring 3.0, a __thread scope__ is available, but is not registered by default. For
more information, see the documentation for
{javadoc-baseurl}/org/springframework/context/support/SimpleThreadScope.html[`SimpleThreadScope`].
For instructions on how to register this or any other custom scope, see
<<beans-factory-scopes-custom-using>>.
===
====
@ -2513,10 +2513,10 @@ object from the relevant scope (for example, an HTTP request) and delegate metho
onto the real object.
[NOTE]
===
====
You __do not__ need to use the `<aop:scoped-proxy/>` in conjunction with beans that are
scoped as `singletons` or `prototypes`.
===
====
The configuration in the following example is only one line, but it is important to
understand the "why" as well as the "how" behind it.
@ -2608,10 +2608,10 @@ By default, when the Spring container creates a proxy for a bean that is marked
the `<aop:scoped-proxy/>` element, __a CGLIB-based class proxy is created__.
[NOTE]
===
====
CGLIB proxies only intercept public method calls! Do not call non-public methods
on such a proxy; they will not be delegated to the actual scoped target object.
===
====
Alternatively, you can configure the Spring container to create standard JDK
interface-based proxies for such scoped beans, by specifying `false` for the value of
@ -2725,11 +2725,11 @@ of the custom `Scope` implementation that you wish to register and use.
Suppose that you write your custom `Scope` implementation, and then register it as below.
[NOTE]
===
====
The example below uses `SimpleThreadScope` which is included with Spring, but not
registered by default. The instructions would be the same for your own custom `Scope`
implementations.
===
====
[source,java,indent=0]
[subs="verbatim,quotes"]
@ -2785,10 +2785,10 @@ of the scope. You can also do the `Scope` registration declaratively, using the
----
[NOTE]
===
====
When you place `<aop:scoped-proxy/>` in a `FactoryBean` implementation, it is the factory
bean itself that is scoped, not the object returned from `getObject()`.
===
====
@ -3051,13 +3051,13 @@ As of Spring 2.5, you have three options for controlling bean lifecycle behavior
annotations>>. You can combine these mechanisms to control a given bean.
[NOTE]
===
====
If multiple lifecycle mechanisms are configured for a bean, and each mechanism is
configured with a different method name, then each configured method is executed in the
order listed below. However, if the same method name is configured - for example,
`init()` for an initialization method - for more than one of these lifecycle mechanisms,
that method is executed once, as explained in the preceding section.
===
====
Multiple lifecycle mechanisms configured for the same bean, with different
initialization methods, are called as follows:
@ -3191,11 +3191,11 @@ above.
[[beans-factory-shutdown]]
==== Shutting down the Spring IoC container gracefully in non-web applications
[NOTE]
===
====
This section applies only to non-web applications. Spring's web-based
`ApplicationContext` implementations already have code in place to shut down the Spring
IoC container gracefully when the relevant web application is shut down.
===
====
If you are using Spring's IoC container in a non-web application environment; for
example, in a rich client desktop environment; you register a shutdown hook with the
@ -3449,13 +3449,13 @@ parent bean id, returns an error. Similarly, the container's internal
abstract.
[NOTE]
===
====
`ApplicationContext` pre-instantiates all singletons by default. Therefore, it is
important (at least for singleton beans) that if you have a (parent) bean definition
which you intend to use only as a template, and this definition specifies a class, you
must make sure to set the __abstract__ attribute to __true__, otherwise the application
context will actually (attempt to) pre-instantiate the `abstract` bean.
===
====
@ -3488,7 +3488,7 @@ interface too. For further details, consult the javadocs of the `BeanPostProcess
registration of `BeanPostProcessors`>>
[NOTE]
===
====
++BeanPostProcessor++s operate on bean (or object) __instances__; that is to say, the
Spring IoC container instantiates a bean instance and __then__ ++BeanPostProcessor++s do
their work.
@ -3502,7 +3502,7 @@ another container, even if both containers are part of the same hierarchy.
To change the actual bean definition (i.e., the __blueprint__ that defines the bean),
you instead need to use a `BeanFactoryPostProcessor` as described in
<<beans-factory-extension-factory-postprocessors>>.
===
====
The `org.springframework.beans.factory.config.BeanPostProcessor` interface consists of
exactly two callback methods. When such a class is registered as a post-processor with
@ -3530,7 +3530,7 @@ Since a ++BeanPostProcessor++ needs to be instantiated early in order to apply t
initialization of other beans in the context, this early type detection is critical.
[NOTE]
===
====
*Programmatically registering BeanPostProcessors*
@ -3544,10 +3544,10 @@ respect the `Ordered` interface__. Here it is the __order of registration__ that
dictates the order of execution. Note also that `BeanPostProcessors` registered
programmatically are always processed before those registered through auto-detection,
regardless of any explicit ordering.
===
====
[NOTE]
===
====
*BeanPostProcessors and AOP auto-proxying*
@ -3571,7 +3571,7 @@ ineligible for auto-proxying or other kinds of bean post-processing. For example
have a dependency annotated with `@Resource` where the field/setter name does not
directly correspond to the declared name of a bean and no name attribute is used, then
Spring will access other beans for matching them by type.
===
====
The following examples show how to write, register, and use `BeanPostProcessors` in an
`ApplicationContext`.
@ -3704,7 +3704,7 @@ consider implementing the `Ordered` interface too. Consult the javadocs of the
`BeanFactoryPostProcessor` and `Ordered` interfaces for more details.
[NOTE]
===
====
If you want to change the actual bean __instances__ (i.e., the objects that are created
from the configuration metadata), then you instead need to use a `BeanPostProcessor`
(described above in <<beans-factory-extension-bpp>>). While it is technically possible
@ -3718,7 +3718,7 @@ you are using container hierarchies. If you define a `BeanFactoryPostProcessor`
container, it will __only__ be applied to the bean definitions in that container. Bean
definitions in one container will not be post-processed by `BeanFactoryPostProcessors`
in another container, even if both containers are part of the same hierarchy.
===
====
A bean factory post-processor is executed automatically when it is declared inside an
`ApplicationContext`, in order to apply changes to the configuration metadata that
@ -3735,14 +3735,14 @@ post-processors, at the appropriate time. You can deploy these post-processor be
you would any other bean.
[NOTE]
===
====
As with ++BeanPostProcessor++s , you typically do not want to configure
++BeanFactoryPostProcessor++s for lazy initialization. If no other bean references a
`Bean(Factory)PostProcessor`, that post-processor will not get instantiated at all.
Thus, marking it for lazy initialization will be ignored, and the
`Bean(Factory)PostProcessor` will be instantiated eagerly even if you set the
`default-lazy-init` attribute to `true` on the declaration of your `<beans />` element.
===
====
[[beans-factory-placeholderconfigurer]]
@ -3894,11 +3894,11 @@ foo.fred.bob.sammy=123
is set to the scalar value `123`.
[NOTE]
===
====
Specified override values are always __literal__ values; they are not translated into
bean references. This convention also applies when the original value in the XML bean
definition specifies a bean reference.
===
====
With the `context` namespace introduced in Spring 2.5, it is possible to configure
property overriding with a dedicated configuration element:
@ -3986,10 +3986,10 @@ Injection for Java) annotations contained in the javax.inject package such as `@
and `@Named`. Details about those annotations can be found in the
<<beans-standard-annotations,relevant section>>.
[NOTE]
===
====
Annotation injection is performed __before__ XML injection, thus the latter
configuration will override the former for properties wired through both approaches.
===
====
As always, you can register them as individual bean definitions, but they can also be
implicitly registered by including the following tag in an XML-based Spring
configuration (notice the inclusion of the `context` namespace):
@ -4019,13 +4019,13 @@ as well as the aforementioned
{javadoc-baseurl}/org/springframework/beans/factory/annotation/RequiredAnnotationBeanPostProcessor.html[`RequiredAnnotationBeanPostProcessor`].)
[NOTE]
===
====
`<context:annotation-config/>` only looks for annotations on beans in the same
application context in which it is defined. This means that, if you put
`<context:annotation-config/>` in a `WebApplicationContext` for a `DispatcherServlet`,
it only checks for `@Autowired` beans in your controllers, and not your services. See
<<mvc-servlet>> for more information.
===
====
@ -4085,10 +4085,10 @@ As expected, you can apply the `@Autowired` annotation to "traditional" setter m
----
[NOTE]
===
====
JSR 330's @Inject annotation can be used in place of Spring's `@Autowired` annotation in
the examples below. See <<beans-standard-annotations,here>> for more details
===
====
You can also apply the annotation to methods with arbitrary names and/or multiple
arguments:
@ -4223,7 +4223,7 @@ indicating __required__ dependencies. This behavior can be changed as demonstrat
----
[NOTE]
===
====
Only __one annotated constructor per-class__ can be marked as __required__, but multiple
non-required constructors can be annotated. In that case, each is considered among the
candidates and Spring uses the __greediest__ constructor whose dependencies can be
@ -4234,7 +4234,7 @@ The __required__ attribute indicates that the property is not required for autow
purposes, the property is ignored if it cannot be autowired. `@Required`, on the other
hand, is stronger in that it enforces the property that was set by any means supported
by the container. If no value is injected, a corresponding exception is raised.
===
====
You can also use `@Autowired` for interfaces that are well-known resolvable
dependencies: `BeanFactory`, `ApplicationContext`, `Environment`, `ResourceLoader`,
@ -4259,12 +4259,12 @@ automatically resolved, with no special setup necessary.
----
[NOTE]
===
====
`@Autowired`, `@Inject`, `@Resource`, and `@Value` annotations are handled by a Spring
`BeanPostProcessor` implementations which in turn means that you __cannot__ apply these
annotations within your own `BeanPostProcessor` or `BeanFactoryPostProcessor` types (if
any). These types must be 'wired up' explicitly via XML or using a Spring `@Bean` method.
===
====
@ -4756,14 +4756,14 @@ name "movieFinder" injected into its setter method:
----
[NOTE]
===
====
The name provided with the annotation is resolved as a bean name by the
`ApplicationContext` of which the `CommonAnnotationBeanPostProcessor` is aware. The
names can be resolved through JNDI if you configure Spring's
{javadoc-baseurl}/org/springframework/jndi/support/SimpleJndiBeanFactory.html[`SimpleJndiBeanFactory`]
explicitly. However, it is recommended that you rely on the default behavior and simply
use Spring's JNDI lookup capabilities to preserve the level of indirection.
===
====
In the exclusive case of `@Resource` usage with no explicit name specified, and similar
to `@Autowired`, `@Resource` finds a primary type match instead of a specific named bean
@ -4830,10 +4830,10 @@ pre-populated upon initialization and cleared upon destruction.
----
[NOTE]
===
====
For details about the effects of combining various lifecycle mechanisms, see
<<beans-factory-lifecycle-combined-effects>>.
===
====
@ -4854,12 +4854,12 @@ type expressions, or your own custom filter criteria to select which classes wil
bean definitions registered with the container.
[NOTE]
===
====
Starting with Spring 3.0, many features provided by the Spring JavaConfig project are
part of the core Spring Framework. This allows you to define beans using Java rather
than using the traditional XML files. Take a look at the `@Configuration`, `@Bean`,
`@Import`, and `@DependsOn` annotations for examples of how to use these new features.
===
====
@ -4983,10 +4983,10 @@ comma/semicolon/space-separated list that includes the parent package of each cl
----
[NOTE]
===
====
for concision, the above may have used the `value` attribute of the
annotation, i.e. `ComponentScan("org.example")`
===
====
The following is an alternative using XML
@ -5016,14 +5016,14 @@ The use of `<context:component-scan>` implicitly enables the functionality of
===
[NOTE]
===
====
The scanning of classpath packages requires the presence of corresponding directory
entries in the classpath. When you build JARs with Ant, make sure that you do __not__
activate the files-only switch of the JAR task. Also, classpath directories may not
get exposed based on security policies in some environments, e.g. standalone apps on
JDK 1.7.0_45 and higher (which requires 'Trusted-Library' setup in your manifests; see
http://stackoverflow.com/questions/19394570/java-jre-7u45-breaks-classloader-getresources).
===
====
Furthermore, the `AutowiredAnnotationBeanPostProcessor` and
`CommonAnnotationBeanPostProcessor` are both included implicitly when you use the
@ -5031,11 +5031,11 @@ component-scan element. That means that the two components are autodetected __an
wired together - all without any bean configuration metadata provided in XML.
[NOTE]
===
====
You can disable the registration of `AutowiredAnnotationBeanPostProcessor` and
`CommonAnnotationBeanPostProcessor` by including the __annotation-config__ attribute
with a value of false.
===
====
@ -5248,13 +5248,13 @@ were detected, the names would be myMovieLister and movieFinderImpl:
----
[NOTE]
===
====
If you do not want to rely on the default bean-naming strategy, you can provide a custom
bean-naming strategy. First, implement the
{javadoc-baseurl}/org/springframework/beans/factory/support/BeanNameGenerator.html[`BeanNameGenerator`]
interface, and be sure to include a default no-arg constructor. Then, provide the
fully-qualified class name when configuring the scanner:
===
====
[source,java,indent=0]
[subs="verbatim,quotes"]
@ -5299,13 +5299,13 @@ within the annotation:
----
[NOTE]
===
====
To provide a custom strategy for scope resolution rather than relying on the
annotation-based approach, implement the
{javadoc-baseurl}/org/springframework/context/annotation/ScopeMetadataResolver.html[`ScopeMetadataResolver`]
interface, and be sure to include a default no-arg constructor. Then, provide the
fully-qualified class name when configuring the scanner:
===
====
[source,java,indent=0]
[subs="verbatim,quotes"]
@ -5396,12 +5396,12 @@ technique:
----
[NOTE]
===
====
As with most annotation-based alternatives, keep in mind that the annotation metadata is
bound to the class definition itself, while the use of XML allows for multiple beans
__of the same type__ to provide variations in their qualifier metadata, because that
metadata is provided per-instance rather than per-class.
===
====
@ -5786,14 +5786,14 @@ definitions within the container. `AnnotationConfigApplicationContext` exposes t
----
[NOTE]
===
====
Remember that `@Configuration` classes are <<beans-meta-annotations,meta-annotated>>
with `@Component`, so they are candidates for component-scanning! In the example above,
assuming that `AppConfig` is declared within the `com.acme` package (or any package
underneath), it will be picked up during the call to `scan()`, and upon `refresh()` all
its `@Bean` methods will be processed and registered as bean definitions within the
container.
===
====
[[beans-java-instantiating-container-web]]
@ -6181,11 +6181,11 @@ In the example above, the `foo` bean receives a reference to `bar` via construct
injection.
[NOTE]
===
====
This method of declaring inter-bean dependencies only works when the `@Bean` method is
declared within a `@Configuration` class. You cannot declare inter-bean dependencies
using plain `@Component` classes.
===
====
[[beans-java-method-injection]]
@ -6285,19 +6285,19 @@ CGLIB classes have been repackaged under org.springframework and included direct
within the spring-core JAR.
[NOTE]
===
====
The behavior could be different according to the scope of your bean. We are talking
about singletons here.
===
====
[NOTE]
===
====
There are a few restrictions due to the fact that CGLIB dynamically adds features at
startup-time:
* Configuration classes should not be final
* They should have a constructor with no arguments
===
====
@ -6650,13 +6650,13 @@ jdbc.password=
----
[NOTE]
===
====
In `system-test-config.xml` above, the `AppConfig<bean/>` does not declare an `id`
element. While it would be acceptable to do so, it is unnecessary given that no other
bean will ever refer to it, and it is unlikely that it will be explicitly fetched from
the container by name. Likewise with the `DataSource` bean - it is only ever autowired
by type, so an explicit bean id is not strictly required.
===
====
--
.[[beans-java-combining-xml-centric-component-scan]] Using <context:component-scan/> to pick up `@Configuration` classes
@ -7090,7 +7090,7 @@ is configured with two PropertySource objects -- one representing the set of JVM
(_a la_ `System.getenv()`).
[NOTE]
===
====
These default property sources are present for `StandardEnvironment`, for use in standalone
applications. {javadoc-baseurl}/org/springframework/web/context/support/StandardServletEnvironment.html[`StandardServletEnvironment`]
is populated with additional default property sources including servlet config and servlet
@ -7098,7 +7098,7 @@ context parameters. {javadoc-baseurl}/org/springframework/web/portlet/context/St
similarly has access to portlet config and portlet context parameters as property sources.
Both can optionally enable a {javadoc-baseurl}/org/springframework/jndi/JndiPropertySource.html[`JndiPropertySource`].
See Javadoc for details.
===
====
Concretely, when using the `StandardEnvironment`, the call to `env.containsProperty("foo")`
will return true if a `foo` system property or `foo` environment variable is present at
@ -7471,7 +7471,7 @@ You can also use the `MessageSourceAware` interface to acquire a reference to an
the application context's `MessageSource` when the bean is created and configured.
[NOTE]
===
====
__As an alternative to `ResourceBundleMessageSource`, Spring provides a
`ReloadableResourceBundleMessageSource` class. This variant supports the same bundle
file format but is more flexible than the standard JDK based
@ -7479,7 +7479,7 @@ file format but is more flexible than the standard JDK based
files from any Spring resource location (not just from the classpath) and supports hot
reloading of bundle property files (while efficiently caching them in between). Check
out the `ReloadableResourceBundleMessageSource` javadocs for details.
===
====
@ -7655,7 +7655,7 @@ called, if there are any emails that should be blacklisted, a custom event of ty
notify appropriate parties.
[NOTE]
===
====
Spring's eventing mechanism is designed for simple communication between Spring beans
within the same application context. However, for more sophisticated enterprise
integration needs, the separately-maintained
@ -7663,7 +7663,7 @@ http://projects.spring.io/spring-integration/[Spring Integration] project provid
complete support for building lightweight,
http://www.enterpriseintegrationpatterns.com[pattern-oriented], event-driven
architectures that build upon the well-known Spring programming model.
===
====
@ -7764,7 +7764,7 @@ JavaDoc) and the corresponding Spring XML bean definition file(s) (typically
application server's deployment directory.
[NOTE]
===
====
Such RAR deployment units are usually self-contained; they do not expose components to
the outside world, not even to other modules of the same application. Interaction with a
RAR-based ApplicationContext usually occurs through JMS destinations that it shares with
@ -7772,7 +7772,7 @@ other modules. A RAR-based ApplicationContext may also, for example, schedule so
reacting to new files in the file system (or the like). If it needs to allow synchronous
access from the outside, it could for example export RMI endpoints, which of course may
be used by other application modules on the same machine.
===
====

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,666 @@
[[resources]]
= Resources
[[resources-introduction]]
== Introduction
Java's standard `java.net.URL` class and standard handlers for various URL prefixes
unfortunately are not quite adequate enough for all access to low-level resources. For
example, there is no standardized `URL` implementation that may be used to access a
resource that needs to be obtained from the classpath, or relative to a
`ServletContext`. While it is possible to register new handlers for specialized `URL`
prefixes (similar to existing handlers for prefixes such as `http:`), this is generally
quite complicated, and the `URL` interface still lacks some desirable functionality,
such as a method to check for the existence of the resource being pointed to.
[[resources-resource]]
== The Resource interface
Spring's `Resource` interface is meant to be a more capable interface for abstracting
access to low-level resources.
[source,java,indent=0]
[subs="verbatim,quotes"]
----
public interface Resource extends InputStreamSource {
boolean exists();
boolean isOpen();
URL getURL() throws IOException;
File getFile() throws IOException;
Resource createRelative(String relativePath) throws IOException;
String getFilename();
String getDescription();
}
----
[source,java,indent=0]
[subs="verbatim,quotes"]
----
public interface InputStreamSource {
InputStream getInputStream() throws IOException;
}
----
Some of the most important methods from the `Resource` interface are:
* `getInputStream()`: locates and opens the resource, returning an `InputStream` for
reading from the resource. It is expected that each invocation returns a fresh
`InputStream`. It is the responsibility of the caller to close the stream.
* `exists()`: returns a `boolean` indicating whether this resource actually exists in
physical form.
* `isOpen()`: returns a `boolean` indicating whether this resource represents a handle
with an open stream. If `true`, the `InputStream` cannot be read multiple times, and
must be read once only and then closed to avoid resource leaks. Will be `false` for
all usual resource implementations, with the exception of `InputStreamResource`.
* `getDescription()`: returns a description for this resource, to be used for error
output when working with the resource. This is often the fully qualified file name or
the actual URL of the resource.
Other methods allow you to obtain an actual `URL` or `File` object representing the
resource (if the underlying implementation is compatible, and supports that
functionality).
The `Resource` abstraction is used extensively in Spring itself, as an argument type in
many method signatures when a resource is needed. Other methods in some Spring APIs
(such as the constructors to various `ApplicationContext` implementations), take a
`String` which in unadorned or simple form is used to create a `Resource` appropriate to
that context implementation, or via special prefixes on the `String` path, allow the
caller to specify that a specific `Resource` implementation must be created and used.
While the `Resource` interface is used a lot with Spring and by Spring, it's actually
very useful to use as a general utility class by itself in your own code, for access to
resources, even when your code doesn't know or care about any other parts of Spring.
While this couples your code to Spring, it really only couples it to this small set of
utility classes, which are serving as a more capable replacement for `URL`, and can be
considered equivalent to any other library you would use for this purpose.
It is important to note that the `Resource` abstraction does not replace functionality:
it wraps it where possible. For example, a `UrlResource` wraps a URL, and uses the
wrapped `URL` to do its work.
[[resources-implementations]]
== Built-in Resource implementations
There are a number of `Resource` implementations that come supplied straight out of the
box in Spring:
[[resources-implementations-urlresource]]
=== UrlResource
The `UrlResource` wraps a `java.net.URL`, and may be used to access any object that is
normally accessible via a URL, such as files, an HTTP target, an FTP target, etc. All
URLs have a standardized `String` representation, such that appropriate standardized
prefixes are used to indicate one URL type from another. This includes `file:` for
accessing filesystem paths, `http:` for accessing resources via the HTTP protocol,
`ftp:` for accessing resources via FTP, etc.
A `UrlResource` is created by Java code explicitly using the `UrlResource` constructor,
but will often be created implicitly when you call an API method which takes a `String`
argument which is meant to represent a path. For the latter case, a JavaBeans
`PropertyEditor` will ultimately decide which type of `Resource` to create. If the path
string contains a few well-known (to it, that is) prefixes such as `classpath:`, it will
create an appropriate specialized `Resource` for that prefix. However, if it doesn't
recognize the prefix, it will assume the this is just a standard URL string, and will
create a `UrlResource`.
[[resources-implementations-classpathresource]]
=== ClassPathResource
This class represents a resource which should be obtained from the classpath. This uses
either the thread context class loader, a given class loader, or a given class for
loading resources.
This `Resource` implementation supports resolution as `java.io.File` if the class path
resource resides in the file system, but not for classpath resources which reside in a
jar and have not been expanded (by the servlet engine, or whatever the environment is)
to the filesystem. To address this the various `Resource` implementations always support
resolution as a `java.net.URL`.
A `ClassPathResource` is created by Java code explicitly using the `ClassPathResource`
constructor, but will often be created implicitly when you call an API method which
takes a `String` argument which is meant to represent a path. For the latter case, a
JavaBeans `PropertyEditor` will recognize the special prefix `classpath:` on the string
path, and create a `ClassPathResource` in that case.
[[resources-implementations-filesystemresource]]
=== FileSystemResource
This is a `Resource` implementation for `java.io.File` handles. It obviously supports
resolution as a `File`, and as a `URL`.
[[resources-implementations-servletcontextresource]]
=== ServletContextResource
This is a `Resource` implementation for `ServletContext` resources, interpreting
relative paths within the relevant web application's root directory.
This always supports stream access and URL access, but only allows `java.io.File` access
when the web application archive is expanded and the resource is physically on the
filesystem. Whether or not it's expanded and on the filesystem like this, or accessed
directly from the JAR or somewhere else like a DB (it's conceivable) is actually
dependent on the Servlet container.
[[resources-implementations-inputstreamresource]]
=== InputStreamResource
A `Resource` implementation for a given `InputStream`. This should only be used if no
specific `Resource` implementation is applicable. In particular, prefer
`ByteArrayResource` or any of the file-based `Resource` implementations where possible.
In contrast to other `Resource` implementations, this is a descriptor for an __already__
opened resource - therefore returning `true` from `isOpen()`. Do not use it if you need
to keep the resource descriptor somewhere, or if you need to read a stream multiple
times.
[[resources-implementations-bytearrayresource]]
=== ByteArrayResource
This is a `Resource` implementation for a given byte array. It creates a
`ByteArrayInputStream` for the given byte array.
It's useful for loading content from any given byte array, without having to resort to a
single-use `InputStreamResource`.
[[resources-resourceloader]]
== The ResourceLoader
The `ResourceLoader` interface is meant to be implemented by objects that can return
(i.e. load) `Resource` instances.
[source,java,indent=0]
[subs="verbatim,quotes"]
----
public interface ResourceLoader {
Resource getResource(String location);
}
----
All application contexts implement the `ResourceLoader` interface, and therefore all
application contexts may be used to obtain `Resource` instances.
When you call `getResource()` on a specific application context, and the location path
specified doesn't have a specific prefix, you will get back a `Resource` type that is
appropriate to that particular application context. For example, assume the following
snippet of code was executed against a `ClassPathXmlApplicationContext` instance:
[source,java,indent=0]
[subs="verbatim,quotes"]
----
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");
----
What would be returned would be a `ClassPathResource`; if the same method was executed
against a `FileSystemXmlApplicationContext` instance, you'd get back a
`FileSystemResource`. For a `WebApplicationContext`, you'd get back a
`ServletContextResource`, and so on.
As such, you can load resources in a fashion appropriate to the particular application
context.
On the other hand, you may also force `ClassPathResource` to be used, regardless of the
application context type, by specifying the special `classpath:` prefix:
[source,java,indent=0]
[subs="verbatim,quotes"]
----
Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");
----
Similarly, one can force a `UrlResource` to be used by specifying any of the standard
`java.net.URL` prefixes:
[source,java,indent=0]
[subs="verbatim,quotes"]
----
Resource template = ctx.getResource("file:///some/resource/path/myTemplate.txt");
----
[source,java,indent=0]
[subs="verbatim,quotes"]
----
Resource template = ctx.getResource("http://myhost.com/resource/path/myTemplate.txt");
----
The following table summarizes the strategy for converting ++String++s to ++Resource++s:
[[resources-resource-strings]]
.Resource strings
|===
| Prefix| Example| Explanation
| classpath:
| `classpath:com/myapp/config.xml`
| Loaded from the classpath.
| file:
| `file:///data/config.xml`
| Loaded as a `URL`, from the filesystem. footnote:[But see also
pass:specialcharacters,macros[<<resources-filesystemresource-caveats>>].]
| http:
| `http://myserver/logo.png`
| Loaded as a `URL`.
| (none)
| `/data/config.xml`
| Depends on the underlying `ApplicationContext`.
|===
[[resources-resourceloaderaware]]
== The ResourceLoaderAware interface
The `ResourceLoaderAware` interface is a special marker interface, identifying objects
that expect to be provided with a `ResourceLoader` reference.
[source,java,indent=0]
[subs="verbatim,quotes"]
----
public interface ResourceLoaderAware {
void setResourceLoader(ResourceLoader resourceLoader);
}
----
When a class implements `ResourceLoaderAware` and is deployed into an application
context (as a Spring-managed bean), it is recognized as `ResourceLoaderAware` by the
application context. The application context will then invoke the
`setResourceLoader(ResourceLoader)`, supplying itself as the argument (remember, all
application contexts in Spring implement the `ResourceLoader` interface).
Of course, since an `ApplicationContext` is a `ResourceLoader`, the bean could also
implement the `ApplicationContextAware` interface and use the supplied application
context directly to load resources, but in general, it's better to use the specialized
`ResourceLoader` interface if that's all that's needed. The code would just be coupled
to the resource loading interface, which can be considered a utility interface, and not
the whole Spring `ApplicationContext` interface.
As of Spring 2.5, you can rely upon autowiring of the `ResourceLoader` as an alternative
to implementing the `ResourceLoaderAware` interface. The "traditional" `constructor` and
`byType` autowiring modes (as described in <<beans-factory-autowire>>) are now capable
of providing a dependency of type `ResourceLoader` for either a constructor argument or
setter method parameter respectively. For more flexibility (including the ability to
autowire fields and multiple parameter methods), consider using the new annotation-based
autowiring features. In that case, the `ResourceLoader` will be autowired into a field,
constructor argument, or method parameter that is expecting the `ResourceLoader` type as
long as the field, constructor, or method in question carries the `@Autowired`
annotation. For more information, see <<beans-autowired-annotation>>.
[[resources-as-dependencies]]
== Resources as dependencies
If the bean itself is going to determine and supply the resource path through some sort
of dynamic process, it probably makes sense for the bean to use the `ResourceLoader`
interface to load resources. Consider as an example the loading of a template of some
sort, where the specific resource that is needed depends on the role of the user. If the
resources are static, it makes sense to eliminate the use of the `ResourceLoader`
interface completely, and just have the bean expose the `Resource` properties it needs,
and expect that they will be injected into it.
What makes it trivial to then inject these properties, is that all application contexts
register and use a special JavaBeans `PropertyEditor` which can convert `String` paths
to `Resource` objects. So if `myBean` has a template property of type `Resource`, it can
be configured with a simple string for that resource, as follows:
[source,xml,indent=0]
[subs="verbatim,quotes"]
----
<bean id="myBean" class="...">
<property name="template" value="some/resource/path/myTemplate.txt"/>
</bean>
----
Note that the resource path has no prefix, so because the application context itself is
going to be used as the `ResourceLoader`, the resource itself will be loaded via a
`ClassPathResource`, `FileSystemResource`, or `ServletContextResource` (as appropriate)
depending on the exact type of the context.
If there is a need to force a specific `Resource` type to be used, then a prefix may be
used. The following two examples show how to force a `ClassPathResource` and a
`UrlResource` (the latter being used to access a filesystem file).
[source,xml,indent=0]
[subs="verbatim,quotes"]
----
<property name="template" value="classpath:some/resource/path/myTemplate.txt">
----
[source,xml,indent=0]
[subs="verbatim,quotes"]
----
<property name="template" value="file:///some/resource/path/myTemplate.txt"/>
----
[[resources-app-ctx]]
== Application contexts and Resource paths
[[resources-app-ctx-construction]]
=== Constructing application contexts
An application context constructor (for a specific application context type) generally
takes a string or array of strings as the location path(s) of the resource(s) such as
XML files that make up the definition of the context.
When such a location path doesn't have a prefix, the specific `Resource` type built from
that path and used to load the bean definitions, depends on and is appropriate to the
specific application context. For example, if you create a
`ClassPathXmlApplicationContext` as follows:
[source,java,indent=0]
[subs="verbatim,quotes"]
----
ApplicationContext ctx = new ClassPathXmlApplicationContext("conf/appContext.xml");
----
The bean definitions will be loaded from the classpath, as a `ClassPathResource` will be
used. But if you create a `FileSystemXmlApplicationContext` as follows:
[source,java,indent=0]
[subs="verbatim,quotes"]
----
ApplicationContext ctx =
new FileSystemXmlApplicationContext("conf/appContext.xml");
----
The bean definition will be loaded from a filesystem location, in this case relative to
the current working directory.
Note that the use of the special classpath prefix or a standard URL prefix on the
location path will override the default type of `Resource` created to load the
definition. So this `FileSystemXmlApplicationContext`...
[source,java,indent=0]
[subs="verbatim,quotes"]
----
ApplicationContext ctx =
new FileSystemXmlApplicationContext("classpath:conf/appContext.xml");
----
... will actually load its bean definitions from the classpath. However, it is still a
`FileSystemXmlApplicationContext`. If it is subsequently used as a `ResourceLoader`, any
unprefixed paths will still be treated as filesystem paths.
[[resources-app-ctx-classpathxml]]
==== Constructing ClassPathXmlApplicationContext instances - shortcuts
The `ClassPathXmlApplicationContext` exposes a number of constructors to enable
convenient instantiation. The basic idea is that one supplies merely a string array
containing just the filenames of the XML files themselves (without the leading path
information), and one __also__ supplies a `Class`; the `ClassPathXmlApplicationContext`
will derive the path information from the supplied class.
An example will hopefully make this clear. Consider a directory layout that looks like
this:
[literal]
[subs="verbatim,quotes"]
----
com/
foo/
services.xml
daos.xml
MessengerService.class
----
A `ClassPathXmlApplicationContext` instance composed of the beans defined in the
`'services.xml'` and `'daos.xml'` could be instantiated like so...
[source,java,indent=0]
[subs="verbatim,quotes"]
----
ApplicationContext ctx = new ClassPathXmlApplicationContext(
new String[] {"services.xml", "daos.xml"}, MessengerService.class);
----
Please do consult the `ClassPathXmlApplicationContext` javadocs for details
on the various constructors.
[[resources-app-ctx-wildcards-in-resource-paths]]
=== Wildcards in application context constructor resource paths
The resource paths in application context constructor values may be a simple path (as
shown above) which has a one-to-one mapping to a target Resource, or alternately may
contain the special "classpath*:" prefix and/or internal Ant-style regular expressions
(matched using Spring's `PathMatcher` utility). Both of the latter are effectively
wildcards
One use for this mechanism is when doing component-style application assembly. All
components can 'publish' context definition fragments to a well-known location path, and
when the final application context is created using the same path prefixed via
`classpath*:`, all component fragments will be picked up automatically.
Note that this wildcarding is specific to use of resource paths in application context
constructors (or when using the `PathMatcher` utility class hierarchy directly), and is
resolved at construction time. It has nothing to do with the `Resource` type itself.
It's not possible to use the `classpath*:` prefix to construct an actual `Resource`, as
a resource points to just one resource at a time.
[[resources-app-ctx-ant-patterns-in-paths]]
==== Ant-style Patterns
When the path location contains an Ant-style pattern, for example:
[literal]
[subs="verbatim"]
----
/WEB-INF/*-context.xml
com/mycompany/**/applicationContext.xml
file:C:/some/path/*-context.xml
classpath:com/mycompany/**/applicationContext.xml
----
... the resolver follows a more complex but defined procedure to try to resolve the
wildcard. It produces a Resource for the path up to the last non-wildcard segment and
obtains a URL from it. If this URL is not a "jar:" URL or container-specific variant
(e.g. " `zip:`" in WebLogic, " `wsjar`" in WebSphere, etc.), then a `java.io.File` is
obtained from it and used to resolve the wildcard by traversing the filesystem. In the
case of a jar URL, the resolver either gets a `java.net.JarURLConnection` from it or
manually parses the jar URL and then traverses the contents of the jar file to resolve
the wildcards.
[[resources-app-ctx-portability]]
===== Implications on portability
If the specified path is already a file URL (either explicitly, or implicitly because
the base `ResourceLoader` is a filesystem one, then wildcarding is guaranteed to work in
a completely portable fashion.
If the specified path is a classpath location, then the resolver must obtain the last
non-wildcard path segment URL via a `Classloader.getResource()` call. Since this is just
a node of the path (not the file at the end) it is actually undefined (in the
`ClassLoader` javadocs) exactly what sort of a URL is returned in this case. In
practice, it is always a `java.io.File` representing the directory, where the classpath
resource resolves to a filesystem location, or a jar URL of some sort, where the
classpath resource resolves to a jar location. Still, there is a portability concern on
this operation.
If a jar URL is obtained for the last non-wildcard segment, the resolver must be able to
get a `java.net.JarURLConnection` from it, or manually parse the jar URL, to be able to
walk the contents of the jar, and resolve the wildcard. This will work in most
environments, but will fail in others, and it is strongly recommended that the wildcard
resolution of resources coming from jars be thoroughly tested in your specific
environment before you rely on it.
[[resources-classpath-wildcards]]
==== The Classpath*: portability classpath*: prefix
When constructing an XML-based application context, a location string may use the
special `classpath*:` prefix:
[source,java,indent=0]
[subs="verbatim,quotes"]
----
ApplicationContext ctx =
new ClassPathXmlApplicationContext("classpath*:conf/appContext.xml");
----
This special prefix specifies that all classpath resources that match the given name
must be obtained (internally, this essentially happens via a
`ClassLoader.getResources(...)` call), and then merged to form the final application
context definition.
[NOTE]
====
The wildcard classpath relies on the `getResources()` method of the underlying
classloader. As most application servers nowadays supply their own classloader
implementation, the behavior might differ especially when dealing with jar files. A
simple test to check if `classpath*` works is to use the classloader to load a file from
within a jar on the classpath:
`getClass().getClassLoader().getResources("<someFileInsideTheJar>")`. Try this test with
files that have the same name but are placed inside two different locations. In case an
inappropriate result is returned, check the application server documentation for
settings that might affect the classloader behavior.
====
The " `classpath*:`" prefix can also be combined with a `PathMatcher` pattern in the
rest of the location path, for example " `classpath*:META-INF/*-beans.xml`". In this
case, the resolution strategy is fairly simple: a ClassLoader.getResources() call is
used on the last non-wildcard path segment to get all the matching resources in the
class loader hierarchy, and then off each resource the same PathMatcher resolution
strategy described above is used for the wildcard subpath.
[[resources-wildcards-in-path-other-stuff]]
==== Other notes relating to wildcards
Please note that `classpath*:` when combined with Ant-style patterns will only work
reliably with at least one root directory before the pattern starts, unless the actual
target files reside in the file system. This means that a pattern like "
`classpath*:*.xml`" will not retrieve files from the root of jar files but rather only
from the root of expanded directories. This originates from a limitation in the JDK's
`ClassLoader.getResources()` method which only returns file system locations for a
passed-in empty string (indicating potential roots to search).
Ant-style patterns with " `classpath:`" resources are not guaranteed to find matching
resources if the root package to search is available in multiple class path locations.
This is because a resource such as
[literal]
[subs="verbatim,quotes"]
----
com/mycompany/package1/service-context.xml
----
may be in only one location, but when a path such as
[literal]
[subs="verbatim,quotes"]
----
classpath:com/mycompany/**/service-context.xml
----
is used to try to resolve it, the resolver will work off the (first) URL returned by
`getResource("com/mycompany")`;. If this base package node exists in multiple
classloader locations, the actual end resource may not be underneath. Therefore,
preferably, use " `classpath*:`" with the same Ant-style pattern in such a case, which
will search all class path locations that contain the root package.
[[resources-filesystemresource-caveats]]
=== FileSystemResource caveats
A `FileSystemResource` that is not attached to a `FileSystemApplicationContext` (that
is, a `FileSystemApplicationContext` is not the actual `ResourceLoader`) will treat
absolute vs. relative paths as you would expect. Relative paths are relative to the
current working directory, while absolute paths are relative to the root of the
filesystem.
For backwards compatibility (historical) reasons however, this changes when the
`FileSystemApplicationContext` is the `ResourceLoader`. The
`FileSystemApplicationContext` simply forces all attached `FileSystemResource` instances
to treat all location paths as relative, whether they start with a leading slash or not.
In practice, this means the following are equivalent:
[source,java,indent=0]
[subs="verbatim,quotes"]
----
ApplicationContext ctx =
new FileSystemXmlApplicationContext("conf/context.xml");
----
[source,java,indent=0]
[subs="verbatim,quotes"]
----
ApplicationContext ctx =
new FileSystemXmlApplicationContext("/conf/context.xml");
----
As are the following: (Even though it would make sense for them to be different, as one
case is relative and the other absolute.)
[source,java,indent=0]
[subs="verbatim,quotes"]
----
FileSystemXmlApplicationContext ctx = ...;
ctx.getResource("some/resource/path/myTemplate.txt");
----
[source,java,indent=0]
[subs="verbatim,quotes"]
----
FileSystemXmlApplicationContext ctx = ...;
ctx.getResource("/some/resource/path/myTemplate.txt");
----
In practice, if true absolute filesystem paths are needed, it is better to forgo the use
of absolute paths with `FileSystemResource` / `FileSystemXmlApplicationContext`, and
just force the use of a `UrlResource`, by using the `file:` URL prefix.
[source,java,indent=0]
[subs="verbatim,quotes"]
----
// actual context type doesn't matter, the Resource will always be UrlResource
ctx.getResource("file:///some/resource/path/myTemplate.txt");
----
[source,java,indent=0]
[subs="verbatim,quotes"]
----
// force this FileSystemXmlApplicationContext to load its definition via a UrlResource
ApplicationContext ctx =
new FileSystemXmlApplicationContext("file:///conf/context.xml");
----

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -386,11 +386,11 @@ loader since the default loader supports either resource `locations` or annotate
+
[NOTE]
===
====
`@ContextConfiguration` provides support for __inheriting__ resource locations or
configuration classes as well as context initializers declared by superclasses by
default.
===
====
+
@ -530,13 +530,13 @@ should be active when loading an `ApplicationContext` for test classes.
+
[NOTE]
===
====
`@ActiveProfiles` provides support for __inheriting__ active bean definition profiles
declared by superclasses by default. It is also possible to resolve active bean
definition profiles programmatically by implementing a custom
<<testcontext-ctx-management-env-profiles-ActiveProfilesResolver,`ActiveProfilesResolver`>>
and registering it via the `resolver` attribute of `@ActiveProfiles`.
===
====
+
@ -757,7 +757,7 @@ conjunction with `@ContextConfiguration`.
+
[NOTE]
===
====
If the default conventions are sufficient for your test configuration, you can avoid
using `@TransactionConfiguration` altogether. In other words, if you have only one
transaction manager -- or if you have multiple transaction managers but the transaction
@ -765,7 +765,7 @@ manager for tests is named "transactionManager" or specified via a
`TransactionManagementConfigurer` -- and if you want transactions to roll back
automatically, then there is no need to annotate your test class with
`@TransactionConfiguration`.
===
====
+
@ -916,7 +916,7 @@ tests and can be used anywhere in the Spring Framework.
.JSR-250 Lifecycle Annotations
[NOTE]
===
====
In the Spring TestContext Framework `@PostConstruct` and `@PreDestroy` may be used with
standard semantics on any application components configured in the `ApplicationContext`;
however, these lifecycle annotations have limited usage within an actual test class.
@ -928,7 +928,7 @@ class. On the other hand, if a method within a test class is annotated with
`@PreDestroy`, that method will __never__ be executed. Within a test class it is
therefore recommended to use test lifecycle callbacks from the underlying test framework
instead of `@PostConstruct` and `@PreDestroy`.
===
====
[[integration-testing-annotations-junit]]
@ -1819,11 +1819,11 @@ annotation and supplying a list of profiles that should be activated when loadin
`ApplicationContext` for the test.
[NOTE]
===
====
`@ActiveProfiles` may be used with any implementation of the new `SmartContextLoader`
SPI, but `@ActiveProfiles` is not supported with implementations of the older
`ContextLoader` SPI.
===
====
Let's take a look at some examples with XML configuration and `@Configuration` classes.
@ -2149,7 +2149,7 @@ the `Environment`'s set of `PropertySources` for the `ApplicationContext` loaded
annotated integration test.
[NOTE]
===
====
`@TestPropertySource` may be used with any implementation of the `SmartContextLoader`
SPI, but `@TestPropertySource` is not supported with implementations of the older
`ContextLoader` SPI.
@ -2157,7 +2157,7 @@ SPI, but `@TestPropertySource` is not supported with implementations of the olde
Implementations of `SmartContextLoader` gain access to merged test property source values
via the `getPropertySourceLocations()` and `getPropertySourceProperties()` methods in
`MergedContextConfiguration`.
===
====
*Declaring test property sources*
@ -2494,7 +2494,7 @@ is much faster.
.Test suites and forked processes
[NOTE]
===
====
The Spring TestContext framework stores application contexts in a __static__ cache. This
means that the context is literally stored in a `static` variable. In other words, if
tests execute in separate processes the static cache will be cleared between each test
@ -2509,7 +2509,7 @@ http://maven.apache.org/plugins/maven-surefire-plugin/test-mojo.html#forkMode[fo
for the Maven Surefire plug-in is set to `always` or `pertest`, the TestContext
framework will not be able to cache application contexts between test classes and the
build process will run significantly slower as a result.
===
====
Since having a large number of application contexts loaded within a given test suite can
cause the suite to take an unnecessarily long time to execute, it is often beneficial to
@ -2678,13 +2678,13 @@ application context for `ExtendedTests` will be loaded only from
.Dirtying a context within a context hierarchy
[NOTE]
===
====
If `@DirtiesContext` is used in a test whose context is configured as part of a context
hierarchy, the `hierarchyMode` flag can be used to control how the context cache is
cleared. For further details consult the discussion of `@DirtiesContext` in
<<integration-testing-annotations-spring,Spring Testing Annotations>> and the
`@DirtiesContext` javadocs.
===
====
--
@ -2726,7 +2726,7 @@ use of `@Autowired` on fields and setter methods. The application context config
is presented after all sample code listings.
[NOTE]
===
====
The dependency injection behavior in the following code listings is not specific to
JUnit. The same DI techniques can be used in conjunction with any testing framework.
@ -2734,7 +2734,7 @@ The following examples make calls to static assertion methods such as `assertNot
but without prepending the call with `Assert`. In such cases, assume that the method was
properly imported through an `import static` declaration that is not shown in the
example.
===
====
The first code listing shows a JUnit-based implementation of the test class that uses
`@Autowired` for field injection.

View File

@ -0,0 +1,249 @@
[[web-integration]]
= Integrating with other web frameworks
[[intro]]
== Introduction
.Spring Web Flow
****
Spring Web Flow (SWF) aims to be the best solution for the management of web application
page flow.
SWF integrates with existing frameworks like Spring MVC and JSF, in both Servlet and
Portlet environments. If you have a business process (or processes) that would benefit
from a conversational model as opposed to a purely request model, then SWF may be the
solution.
SWF allows you to capture logical page flows as self-contained modules that are reusable
in different situations, and as such is ideal for building web application modules that
guide the user through controlled navigations that drive business processes.
For more information about SWF, consult the
http://projects.spring.io/spring-webflow/[Spring Web Flow website].
****
This chapter details Spring's integration with third party web frameworks, such as
http://www.oracle.com/technetwork/java/javaee/javaserverfaces-139869.html[JSF].
One of the core value propositions of the Spring Framework is that of enabling
__choice__. In a general sense, Spring does not force one to use or buy into any
particular architecture, technology, or methodology (although it certainly recommends
some over others). This freedom to pick and choose the architecture, technology, or
methodology that is most relevant to a developer and their development team is
arguably most evident in the web area, where Spring provides its own web framework
(<<mvc,Spring MVC>>), while at the same time providing integration with a number of
popular third party web frameworks. This allows one to continue to leverage any and all
of the skills one may have acquired in a particular web framework such as JSF, while
at the same time being able to enjoy the benefits afforded by Spring in other areas such
as data access, declarative transaction management, and flexible configuration and
application assembly.
Having dispensed with the woolly sales patter (c.f. the previous paragraph), the
remainder of this chapter will concentrate upon the meaty details of integrating your
favorite web framework with Spring. One thing that is often commented upon by developers
coming to Java from other languages is the seeming super-abundance of web frameworks
available in Java. There are indeed a great number of web frameworks in the Java space;
in fact there are far too many to cover with any semblance of detail in a single
chapter. This chapter thus picks four of the more popular web frameworks in Java,
starting with the Spring configuration that is common to all of the supported web
frameworks, and then detailing the specific integration options for each supported web
framework.
[NOTE]
====
Please note that this chapter does not attempt to explain how to use any of the
supported web frameworks. For example, if you want to use JSF for the presentation
layer of your web application, the assumption is that you are already familiar with
JSF itself. If you need further details about any of the supported web frameworks
themselves, please do consult <<web-integration-resources>> at the end of this chapter.
====
[[web-integration-common]]
== Common configuration
Before diving into the integration specifics of each supported web framework, let us
first take a look at the Spring configuration that is __not__ specific to any one web
framework. (This section is equally applicable to Spring's own web framework, Spring
MVC.)
One of the concepts (for want of a better word) espoused by (Spring's) lightweight
application model is that of a layered architecture. Remember that in a 'classic'
layered architecture, the web layer is but one of many layers; it serves as one of the
entry points into a server side application and it delegates to service objects
(facades) defined in a service layer to satisfy business specific (and
presentation-technology agnostic) use cases. In Spring, these service objects, any other
business-specific objects, data access objects, etc. exist in a distinct 'business
context', which contains __no__ web or presentation layer objects (presentation objects
such as Spring MVC controllers are typically configured in a distinct 'presentation
context'). This section details how one configures a Spring container (a
`WebApplicationContext`) that contains all of the 'business beans' in one's application.
On to specifics: all that one need do is to declare a
{javadoc-baseurl}/org/springframework/web/context/ContextLoaderListener.html[`ContextLoaderListener`]
in the standard Java EE servlet `web.xml` file of one's web application, and add a
`contextConfigLocation`<context-param/> section (in the same file) that defines which
set of Spring XML configuration files to load.
Find below the <listener/> configuration:
[source,xml,indent=0]
[subs="verbatim,quotes"]
----
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
----
Find below the <context-param/> configuration:
[source,xml,indent=0]
[subs="verbatim,quotes"]
----
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>
----
If you don't specify the `contextConfigLocation` context parameter, the
`ContextLoaderListener` will look for a file called `/WEB-INF/applicationContext.xml` to
load. Once the context files are loaded, Spring creates a
{javadoc-baseurl}/org/springframework/web/context/WebApplicationContext.html[`WebApplicationContext`]
object based on the bean definitions and stores it in the `ServletContext` of the web
application.
All Java web frameworks are built on top of the Servlet API, and so one can use the
following code snippet to get access to this 'business context' `ApplicationContext`
created by the `ContextLoaderListener`.
[source,java,indent=0]
[subs="verbatim,quotes"]
----
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
----
The
{javadoc-baseurl}/org/springframework/web/context/support/WebApplicationContextUtils.html[`WebApplicationContextUtils`]
class is for convenience, so you don't have to remember the name of the `ServletContext`
attribute. Its __getWebApplicationContext()__ method will return `null` if an object
doesn't exist under the `WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE`
key. Rather than risk getting `NullPointerExceptions` in your application, it's better
to use the `getRequiredWebApplicationContext()` method. This method throws an exception
when the `ApplicationContext` is missing.
Once you have a reference to the `WebApplicationContext`, you can retrieve beans by
their name or type. Most developers retrieve beans by name and then cast them to one of
their implemented interfaces.
Fortunately, most of the frameworks in this section have simpler ways of looking up
beans. Not only do they make it easy to get beans from a Spring container, but they also
allow you to use dependency injection on their controllers. Each web framework section
has more detail on its specific integration strategies.
[[jsf]]
== JavaServer Faces 1.2
JavaServer Faces (JSF) is the JCP's standard component-based, event-driven web user
interface framework. As of Java EE 5, it is an official part of the Java EE umbrella.
For a popular JSF runtime as well as for popular JSF component libraries, check out the
http://myfaces.apache.org/[Apache MyFaces project]. The MyFaces project also provides
common JSF extensions such as http://myfaces.apache.org/orchestra/[MyFaces Orchestra]:
a Spring-based JSF extension that provides rich conversation scope support.
[NOTE]
====
Spring Web Flow 2.0 provides rich JSF support through its newly established Spring Faces
module, both for JSF-centric usage (as described in this section) and for Spring-centric
usage (using JSF views within a Spring MVC dispatcher). Check out the
http://projects.spring.io/spring-webflow[Spring Web Flow website] for details!
====
The key element in Spring's JSF integration is the JSF `ELResolver` mechanism.
[[jsf-springbeanfaceselresolver]]
=== SpringBeanFacesELResolver (JSF 1.2+)
`SpringBeanFacesELResolver` is a JSF 1.2 compliant `ELResolver` implementation,
integrating with the standard Unified EL as used by JSF 1.2 and JSP 2.1. Like
`SpringBeanVariableResolver`, it delegates to the Spring's 'business context'
`WebApplicationContext` __first__, then to the default resolver of the underlying JSF
implementation.
Configuration-wise, simply define `SpringBeanFacesELResolver` in your JSF 1.2
__faces-context.xml__ file:
[source,xml,indent=0]
[subs="verbatim,quotes"]
----
<faces-config>
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
...
</application>
</faces-config>
----
[[jsf-facescontextutils]]
=== FacesContextUtils
A custom `VariableResolver` works well when mapping one's properties to beans
in __faces-config.xml__, but at times one may need to grab a bean explicitly. The
{javadoc-baseurl}/org/springframework/web/jsf/FacesContextUtils.html[`FacesContextUtils`]
class makes this easy. It is similar to `WebApplicationContextUtils`, except that it
takes a `FacesContext` parameter rather than a `ServletContext` parameter.
[source,java,indent=0]
[subs="verbatim,quotes"]
----
ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
----
[[struts]]
== Apache Struts 2.x
Invented by Craig McClanahan, http://struts.apache.org[Struts] is an open source project
hosted by the Apache Software Foundation. At the time, it greatly simplified the
JSP/Servlet programming paradigm and won over many developers who were using proprietary
frameworks. It simplified the programming model, it was open source (and thus free as in
beer), and it had a large community, which allowed the project to grow and become popular
among Java web developers.
Check out the Struts
https://struts.apache.org/release/2.3.x/docs/spring-plugin.html[Spring Plugin] for the
built-in Spring integration shipped with Struts.
[[tapestry]]
== Tapestry 5.x
From the http://tapestry.apache.org/[Tapestry homepage]:
Tapestry is a "__Component oriented framework for creating dynamic, robust,
highly scalable web applications in Java.__"
While Spring has its own <<mvc,powerful web layer>>, there are a number of unique
advantages to building an enterprise Java application using a combination of Tapestry
for the web user interface and the Spring container for the lower layers.
For more information, check out Tapestry's dedicated
https://tapestry.apache.org/integrating-with-spring-framework.html[integration module for
Spring].
[[web-integration-resources]]
== Further Resources
Find below links to further resources about the various web frameworks described in this
chapter.
* The http://www.oracle.com/technetwork/java/javaee/javaserverfaces-139869.html[JSF] homepage
* The http://struts.apache.org/[Struts] homepage
* The http://tapestry.apache.org/[Tapestry] homepage

View File

@ -1103,14 +1103,14 @@ arguments can be used in arbitrary order with the only exception of `BindingResu
arguments. This is described in the next section.
[NOTE]
===
====
Spring 3.1 introduced a new set of support classes for `@RequestMapping` methods called
`RequestMappingHandlerMapping` and `RequestMappingHandlerAdapter` respectively. They are
recommended for use and even required to take advantage of new features in Spring MVC
3.1 and going forward. The new support classes are enabled by default from the MVC
namespace and with use of the MVC Java config but must be configured explicitly if using
neither.
===
====
[[mvc-ann-arguments]]
@ -1124,11 +1124,11 @@ The following are the supported method arguments:
`null`.
[NOTE]
===
====
Session access may not be thread-safe, in particular in a Servlet environment. Consider
setting the ++RequestMappingHandlerAdapter++'s "synchronizeOnSession" flag to "true" if
multiple requests are allowed to access a session concurrently.
===
====
* `org.springframework.web.context.request.WebRequest` or
`org.springframework.web.context.request.NativeWebRequest`. Allows for generic
@ -1380,11 +1380,11 @@ will be raised. The exception is handled in the `DefaultHandlerExceptionResolver
sends a `400` error back to the client.
[NOTE]
===
====
Also see <<mvc-config-enable>> for
information on configuring message converters and a validator through the MVC namespace
or the MVC Java config.
===
====
[[mvc-ann-responsebody]]
@ -1740,12 +1740,12 @@ and wraps the `ServletRequest` in order to make the form data available through
`ServletRequest.getParameter{asterisk}()` family of methods.
[NOTE]
===
====
As `HttpPutFormContentFilter` consumes the body of the request, it should not be
configured for PUT or PATCH URLs that rely on other converters for
`application/x-www-form-urlencoded`. This includes `@RequestBody MultiValueMap<String,
String>` and `HttpEntity<MultiValueMap<String, String>>`.
===
====
[[mvc-ann-cookievalue]]
@ -2031,12 +2031,12 @@ the view class or interface to be used:
----
[NOTE]
===
====
Note that despite `@JsonView` allowing for more than one class to
be specified, the use on a controller method is only supported with
exactly one class argument. Consider the use of a composite interface
if you need to enable multiple views.
===
====
For controllers relying on view resolution, simply add the serialization view class
to the model:
@ -2180,12 +2180,12 @@ an exception. It is handled by a matching `@ExceptionHandler` method in the same
controller or by one of the configured `HandlerExceptionResolver` instances.
[NOTE]
===
====
Under the covers, when a `Callable` raises an Exception, Spring MVC still dispatches to
the Servlet container to resume processing. The only difference is that the result of
executing the `Callable` is an `Exception` that must be processed with the configured
`HandlerExceptionResolver` instances.
===
====
When using a `DeferredResult`, you have a choice of calling its `setErrorResult(Object)`
method and provide an `Exception` or any other Object you'd like to use as the result.
@ -2447,10 +2447,10 @@ If the current time is outside office hours, the user is redirected to a static
file that says, for example, you can only access the website during office hours.
[NOTE]
===
====
When using the `RequestMappingHandlerMapping` the actual handler is an instance of
`HandlerMethod` which identifies the specific controller method that will be invoked.
===
====
As you can see, the Spring adapter class `HandlerInterceptorAdapter` makes it easier to
extend the `HandlerInterceptor` interface.
@ -2582,13 +2582,13 @@ As you can see, you can identify a parent view, from which all views in the prop
file "extend". This way you can specify a default view class, for example.
[NOTE]
===
====
Subclasses of `AbstractCachingViewResolver` cache view instances that they resolve.
Caching improves performance of certain view technologies. It's possible to turn off the
cache by setting the `cache` property to `false`. Furthermore, if you must refresh a
certain view at runtime (for example when a Velocity template is modified), you can use
the `removeFromCache(String viewName, Locale loc)` method.
===
====
@ -2865,10 +2865,10 @@ extension but with the `Accept` header set to the preferred media-type, and the
resolution of request to views would occur.
[NOTE]
===
====
If `ContentNegotiatingViewResolver`'s list of ViewResolvers is not configured
explicitly, it automatically uses any ViewResolvers defined in the application context.
===
====
The corresponding controller code that returns an Atom RSS feed for a URI of the form
`http://localhost/content.atom` or `http://localhost/content` with an `Accept` header of
@ -3081,9 +3081,9 @@ by implementing `HandlerMethodMappingNamingStrategy` and configuring it on your
a name attribute that can be used to override the default strategy.
[NOTE]
===
====
The assigned request mapping names are logged at TRACE level on startup.
===
====
The Spring JSP tag library provides a function called `mvcUrl` that can be used to
prepare links to controller methods based on this mechanism.
@ -4930,7 +4930,7 @@ Here is an example:
----
[NOTE]
===
====
An application should have only one configuration extending `DelegatingWebMvcConfiguration`
or a single `@EnableWebMvc` annotated class, since they both register the same underlying
beans.
@ -4938,7 +4938,7 @@ beans.
Modifying beans in this way does not prevent you from using any of the higher-level
constructs shown earlier in this section. `WebMvcConfigurerAdapter` subclasses and
`WebMvcConfigurer` implementations are still being used.
===
====

File diff suppressed because it is too large Load Diff

View File

@ -21,7 +21,7 @@ or JSTL is done using a normal view resolver defined in the `WebApplicationConte
Furthermore, of course you need to write some JSPs that will actually render the view.
[NOTE]
===
====
Setting up your application to use JSTL is a common source of error, mainly caused by
confusion over the different servlet spec., JSP and JSTL version numbers, what they mean
and how to declare the taglibs correctly. The article
@ -30,7 +30,7 @@ to Reference and Use JSTL in your Web Application] provides a useful guide to th
pitfalls and how to avoid them. Note that as of Spring 3.0, the minimum supported
servlet version is 2.4 (JSP 2.0 and JSTL 1.1), which reduces the scope for confusion
somewhat.
===
====
@ -857,10 +857,10 @@ applications using Spring. The following describes in a broad way how to do this
[NOTE]
===
====
This section focuses on Spring's support for Tiles v3 in the
`org.springframework.web.servlet.view.tiles3` package.
===
====
[[view-tiles-dependencies]]
@ -921,10 +921,10 @@ With this configuration, `tiles_fr_FR.xml` will be used for requests with the `f
and `tiles.xml` will be used by default.
[NOTE]
===
====
Since underscores are used to indicate locales, it is recommended to avoid using
them otherwise in the file names for Tiles definitions.
===
====
[[view-tiles-url]]
@ -1094,10 +1094,10 @@ definition to your `'{asterisk}-servlet.xml'` as shown below:
----
[NOTE]
===
====
For non web-apps add a `VelocityConfigurationFactoryBean` or a
`FreeMarkerConfigurationFactoryBean` to your application context definition file.
===
====

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff