diff --git a/src/asciidoc/aop-api.adoc b/src/asciidoc/aop-api.adoc
new file mode 100644
index 000000000000..379520025243
--- /dev/null
+++ b/src/asciidoc/aop-api.adoc
@@ -0,0 +1,1751 @@
+[[aop-api]]
+== Spring AOP APIs
+
+
+
+
+[[aop-api-introduction]]
+=== Introduction
+The previous chapter described the Spring's support for AOP using
+@AspectJ and schema-based aspect definitions. In this chapter we discuss the lower-level
+Spring AOP APIs and the AOP support used in Spring 1.2 applications. For new
+applications, we recommend the use of the Spring 2.0 and later AOP support described in
+the previous chapter, but when working with existing applications, or when reading books
+and articles, you may come across Spring 1.2 style examples. Spring 4.0 is backwards
+compatible with Spring 1.2 and everything described in this chapter is fully supported
+in Spring 4.0.
+
+
+
+
+[[aop-api-pointcuts]]
+=== Pointcut API in Spring
+Let's look at how Spring handles the crucial pointcut concept.
+
+
+
+[[aop-api-concepts]]
+==== Concepts
+Spring's pointcut model enables pointcut reuse independent of advice types. It's
+possible to target different advice using the same pointcut.
+
+The `org.springframework.aop.Pointcut` interface is the central interface, used to
+target advices to particular classes and methods. The complete interface is shown below:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public interface Pointcut {
+
+ ClassFilter getClassFilter();
+
+ MethodMatcher getMethodMatcher();
+
+ }
+----
+
+Splitting the `Pointcut` interface into two parts allows reuse of class and method
+matching parts, and fine-grained composition operations (such as performing a "union"
+with another method matcher).
+
+The `ClassFilter` interface is used to restrict the pointcut to a given set of target
+classes. If the `matches()` method always returns true, all target classes will be
+matched:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public interface ClassFilter {
+
+ boolean matches(Class clazz);
+ }
+----
+
+The `MethodMatcher` interface is normally more important. The complete interface is
+shown below:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public interface MethodMatcher {
+
+ boolean matches(Method m, Class targetClass);
+
+ boolean isRuntime();
+
+ boolean matches(Method m, Class targetClass, Object[] args);
+ }
+----
+
+The `matches(Method, Class)` method is used to test whether this pointcut will ever
+match a given method on a target class. This evaluation can be performed when an AOP
+proxy is created, to avoid the need for a test on every method invocation. If the
+2-argument matches method returns true for a given method, and the `isRuntime()` method
+for the MethodMatcher returns true, the 3-argument matches method will be invoked on
+every method invocation. This enables a pointcut to look at the arguments passed to the
+method invocation immediately before the target advice is to execute.
+
+Most MethodMatchers are static, meaning that their `isRuntime()` method returns false.
+In this case, the 3-argument matches method will never be invoked.
+
+[TIP]
+====
+
+If possible, try to make pointcuts static, allowing the AOP framework to cache the
+results of pointcut evaluation when an AOP proxy is created.
+====
+
+
+
+[[aop-api-pointcut-ops]]
+==== Operations on pointcuts
+Spring supports operations on pointcuts: notably, __union__ and __intersection__.
+
+* Union means the methods that either pointcut matches.
+* Intersection means the methods that both pointcuts match.
+* Union is usually more useful.
+* Pointcuts can be composed using the static methods in the
+ __org.springframework.aop.support.Pointcuts__ class, or using the
+ __ComposablePointcut__ class in the same package. However, using AspectJ pointcut
+ expressions is usually a simpler approach.
+
+
+
+[[aop-api-pointcuts-aspectj]]
+==== AspectJ expression pointcuts
+Since 2.0, the most important type of pointcut used by Spring is
+`org.springframework.aop.aspectj.AspectJExpressionPointcut`. This is a pointcut that
+uses an AspectJ supplied library to parse an AspectJ pointcut expression string.
+
+See the previous chapter for a discussion of supported AspectJ pointcut primitives.
+
+
+
+[[aop-api-pointcuts-impls]]
+==== Convenience pointcut implementations
+Spring provides several convenient pointcut implementations. Some can be used out of the
+box; others are intended to be subclassed in application-specific pointcuts.
+
+
+[[aop-api-pointcuts-static]]
+===== Static pointcuts
+Static pointcuts are based on method and target class, and cannot take into account the
+method's arguments. Static pointcuts are sufficient - __and best__ - for most usages.
+It's possible for Spring to evaluate a static pointcut only once, when a method is first
+invoked: after that, there is no need to evaluate the pointcut again with each method
+invocation.
+
+Let's consider some static pointcut implementations included with Spring.
+
+[[aop-api-pointcuts-regex]]
+====== Regular expression pointcuts
+One obvious way to specify static pointcuts is regular expressions. Several AOP
+frameworks besides Spring make this possible.
+`org.springframework.aop.support.JdkRegexpMethodPointcut` is a generic regular
+expression pointcut, using the regular expression support in JDK 1.4+.
+
+Using the `JdkRegexpMethodPointcut` class, you can provide a list of pattern Strings. If
+any of these is a match, the pointcut will evaluate to true. (So the result is
+effectively the union of these pointcuts.)
+
+The usage is shown below:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+ .*set.*
+ .*absquatulate
+
+
+
+----
+
+Spring provides a convenience class, `RegexpMethodPointcutAdvisor`, that allows us to
+also reference an Advice (remember that an Advice can be an interceptor, before advice,
+throws advice etc.). Behind the scenes, Spring will use a `JdkRegexpMethodPointcut`.
+Using `RegexpMethodPointcutAdvisor` simplifies wiring, as the one bean encapsulates both
+pointcut and advice, as shown below:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+ .*set.*
+ .*absquatulate
+
+
+
+----
+
+__RegexpMethodPointcutAdvisor__ can be used with any Advice type.
+
+[[aop-api-pointcuts-attribute-driven]]
+====== Attribute-driven pointcuts
+An important type of static pointcut is a __metadata-driven__ pointcut. This uses the
+values of metadata attributes: typically, source-level metadata.
+
+
+[[aop-api-pointcuts-dynamic]]
+===== Dynamic pointcuts
+Dynamic pointcuts are costlier to evaluate than static pointcuts. They take into account
+method __arguments__, as well as static information. This means that they must be
+evaluated with every method invocation; the result cannot be cached, as arguments will
+vary.
+
+The main example is the `control flow` pointcut.
+
+[[aop-api-pointcuts-cflow]]
+====== Control flow pointcuts
+Spring control flow pointcuts are conceptually similar to AspectJ __cflow__ pointcuts,
+although less powerful. (There is currently no way to specify that a pointcut executes
+below a join point matched by another pointcut.) A control flow pointcut matches the
+current call stack. For example, it might fire if the join point was invoked by a method
+in the `com.mycompany.web` package, or by the `SomeCaller` class. Control flow pointcuts
+are specified using the `org.springframework.aop.support.ControlFlowPointcut` class.
+[NOTE]
+====
+Control flow pointcuts are significantly more expensive to evaluate at runtime than even
+other dynamic pointcuts. In Java 1.4, the cost is about 5 times that of other dynamic
+pointcuts.
+====
+
+
+
+[[aop-api-pointcuts-superclasses]]
+==== Pointcut superclasses
+Spring provides useful pointcut superclasses to help you to implement your own pointcuts.
+
+Because static pointcuts are most useful, you'll probably subclass
+StaticMethodMatcherPointcut, as shown below. This requires implementing just one
+abstract method (although it's possible to override other methods to customize behavior):
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ class TestStaticPointcut extends StaticMethodMatcherPointcut {
+
+ public boolean matches(Method m, Class targetClass) {
+ // return true if custom criteria match
+ }
+ }
+----
+
+There are also superclasses for dynamic pointcuts.
+
+You can use custom pointcuts with any advice type in Spring 1.0 RC2 and above.
+
+
+
+[[aop-api-pointcuts-custom]]
+==== Custom pointcuts
+Because pointcuts in Spring AOP are Java classes, rather than language features (as in
+AspectJ) it's possible to declare custom pointcuts, whether static or dynamic. Custom
+pointcuts in Spring can be arbitrarily complex. However, using the AspectJ pointcut
+expression language is recommended if possible.
+
+[NOTE]
+====
+Later versions of Spring may offer support for "semantic pointcuts" as offered by JAC:
+for example, "all methods that change instance variables in the target object."
+====
+
+
+
+
+[[aop-api-advice]]
+=== Advice API in Spring
+Let's now look at how Spring AOP handles advice.
+
+
+
+[[aop-api-advice-lifecycle]]
+==== Advice lifecycles
+Each advice is a Spring bean. An advice instance can be shared across all advised
+objects, or unique to each advised object. This corresponds to __per-class__ or
+__per-instance__ advice.
+
+Per-class advice is used most often. It is appropriate for generic advice such as
+transaction advisors. These do not depend on the state of the proxied object or add new
+state; they merely act on the method and arguments.
+
+Per-instance advice is appropriate for introductions, to support mixins. In this case,
+the advice adds state to the proxied object.
+
+It's possible to use a mix of shared and per-instance advice in the same AOP proxy.
+
+
+
+[[aop-api-advice-types]]
+==== Advice types in Spring
+Spring provides several advice types out of the box, and is extensible to support
+arbitrary advice types. Let us look at the basic concepts and standard advice types.
+
+
+[[aop-api-advice-around]]
+===== Interception around advice
+The most fundamental advice type in Spring is __interception around advice__.
+
+Spring is compliant with the AOP Alliance interface for around advice using method
+interception. MethodInterceptors implementing around advice should implement the
+following interface:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public interface MethodInterceptor extends Interceptor {
+
+ Object invoke(MethodInvocation invocation) throws Throwable;
+ }
+----
+
+The `MethodInvocation` argument to the `invoke()` method exposes the method being
+invoked; the target join point; the AOP proxy; and the arguments to the method. The
+`invoke()` method should return the invocation's result: the return value of the join
+point.
+
+A simple `MethodInterceptor` implementation looks as follows:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class DebugInterceptor implements MethodInterceptor {
+
+ public Object invoke(MethodInvocation invocation) throws Throwable {
+ System.out.println("Before: invocation=[" + invocation + "]");
+ Object rval = invocation.proceed();
+ System.out.println("Invocation returned");
+ return rval;
+ }
+ }
+----
+
+Note the call to the MethodInvocation's `proceed()` method. This proceeds down the
+interceptor chain towards the join point. Most interceptors will invoke this method, and
+return its return value. However, a MethodInterceptor, like any around advice, can
+return a different value or throw an exception rather than invoke the proceed method.
+However, you don't want to do this without good reason!
+
+[NOTE]
+====
+MethodInterceptors offer interoperability with other AOP Alliance-compliant AOP
+implementations. The other advice types discussed in the remainder of this section
+implement common AOP concepts, but in a Spring-specific way. While there is an advantage
+in using the most specific advice type, stick with MethodInterceptor around advice if
+you are likely to want to run the aspect in another AOP framework. Note that pointcuts
+are not currently interoperable between frameworks, and the AOP Alliance does not
+currently define pointcut interfaces.
+====
+
+
+[[aop-api-advice-before]]
+===== Before advice
+A simpler advice type is a __before advice__. This does not need a `MethodInvocation`
+object, since it will only be called before entering the method.
+
+The main advantage of a before advice is that there is no need to invoke the `proceed()`
+method, and therefore no possibility of inadvertently failing to proceed down the
+interceptor chain.
+
+The `MethodBeforeAdvice` interface is shown below. (Spring's API design would allow for
+field before advice, although the usual objects apply to field interception and it's
+unlikely that Spring will ever implement it).
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public interface MethodBeforeAdvice extends BeforeAdvice {
+
+ void before(Method m, Object[] args, Object target) throws Throwable;
+ }
+----
+
+Note the return type is `void`. Before advice can insert custom behavior before the join
+point executes, but cannot change the return value. If a before advice throws an
+exception, this will abort further execution of the interceptor chain. The exception
+will propagate back up the interceptor chain. If it is unchecked, or on the signature of
+the invoked method, it will be passed directly to the client; otherwise it will be
+wrapped in an unchecked exception by the AOP proxy.
+
+An example of a before advice in Spring, which counts all method invocations:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class CountingBeforeAdvice implements MethodBeforeAdvice {
+
+ private int count;
+
+ public void before(Method m, Object[] args, Object target) throws Throwable {
+ ++count;
+ }
+
+ public int getCount() {
+ return count;
+ }
+ }
+----
+
+[TIP]
+====
+
+Before advice can be used with any pointcut.
+====
+
+
+[[aop-api-advice-throws]]
+===== Throws advice
+__Throws advice__ is invoked after the return of the join point if the join point threw
+an exception. Spring offers typed throws advice. Note that this means that the
+`org.springframework.aop.ThrowsAdvice` interface does not contain any methods: It is a
+tag interface identifying that the given object implements one or more typed throws
+advice methods. These should be in the form of:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ afterThrowing([Method, args, target], subclassOfThrowable)
+----
+
+Only the last argument is required. The method signatures may have either one or four
+arguments, depending on whether the advice method is interested in the method and
+arguments. The following classes are examples of throws advice.
+
+The advice below is invoked if a `RemoteException` is thrown (including subclasses):
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class RemoteThrowsAdvice implements ThrowsAdvice {
+
+ public void afterThrowing(RemoteException ex) throws Throwable {
+ // Do something with remote exception
+ }
+ }
+----
+
+The following advice is invoked if a `ServletException` is thrown. Unlike the above
+advice, it declares 4 arguments, so that it has access to the invoked method, method
+arguments and target object:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class ServletThrowsAdviceWithArguments implements ThrowsAdvice {
+
+ public void afterThrowing(Method m, Object[] args, Object target, ServletException ex) {
+ // Do something with all arguments
+ }
+ }
+----
+
+The final example illustrates how these two methods could be used in a single class,
+which handles both `RemoteException` and `ServletException`. Any number of throws advice
+methods can be combined in a single class.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public static class CombinedThrowsAdvice implements ThrowsAdvice {
+
+ public void afterThrowing(RemoteException ex) throws Throwable {
+ // Do something with remote exception
+ }
+
+ public void afterThrowing(Method m, Object[] args, Object target, ServletException ex) {
+ // Do something with all arguments
+ }
+ }
+----
+
+[NOTE]
+====
+If a throws-advice method throws an exception itself, it will override the
+original exception (i.e. change the exception thrown to the user). The overriding
+exception will typically be a RuntimeException; this is compatible with any method
+signature. However, if a throws-advice method throws a checked exception, it will have
+to match the declared exceptions of the target method and is hence to some degree
+coupled to specific target method signatures. __Do not throw an undeclared checked
+exception that is incompatible with the target method's signature!__
+====
+
+[TIP]
+====
+
+Throws advice can be used with any pointcut.
+====
+
+
+[[aop-api-advice-after-returning]]
+===== After Returning advice
+An after returning advice in Spring must implement the
+__org.springframework.aop.AfterReturningAdvice__ interface, shown below:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public interface AfterReturningAdvice extends Advice {
+
+ void afterReturning(Object returnValue, Method m, Object[] args, Object target)
+ throws Throwable;
+ }
+----
+
+An after returning advice has access to the return value (which it cannot modify),
+invoked method, methods arguments and target.
+
+The following after returning advice counts all successful method invocations that have
+not thrown exceptions:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class CountingAfterReturningAdvice implements AfterReturningAdvice {
+
+ private int count;
+
+ public void afterReturning(Object returnValue, Method m, Object[] args, Object target)
+ throws Throwable {
+ ++count;
+ }
+
+ public int getCount() {
+ return count;
+ }
+ }
+----
+
+This advice doesn't change the execution path. If it throws an exception, this will be
+thrown up the interceptor chain instead of the return value.
+
+[TIP]
+====
+
+After returning advice can be used with any pointcut.
+====
+
+
+[[aop-api-advice-introduction]]
+===== Introduction advice
+Spring treats introduction advice as a special kind of interception advice.
+
+Introduction requires an `IntroductionAdvisor`, and an `IntroductionInterceptor`,
+implementing the following interface:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public interface IntroductionInterceptor extends MethodInterceptor {
+
+ boolean implementsInterface(Class intf);
+ }
+----
+
+The `invoke()` method inherited from the AOP Alliance `MethodInterceptor` interface must
+implement the introduction: that is, if the invoked method is on an introduced
+interface, the introduction interceptor is responsible for handling the method call - it
+cannot invoke `proceed()`.
+
+Introduction advice cannot be used with any pointcut, as it applies only at class,
+rather than method, level. You can only use introduction advice with the
+`IntroductionAdvisor`, which has the following methods:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public interface IntroductionAdvisor extends Advisor, IntroductionInfo {
+
+ ClassFilter getClassFilter();
+
+ void validateInterfaces() throws IllegalArgumentException;
+ }
+
+ public interface IntroductionInfo {
+
+ Class[] getInterfaces();
+ }
+----
+
+There is no `MethodMatcher`, and hence no `Pointcut`, associated with introduction
+advice. Only class filtering is logical.
+
+The `getInterfaces()` method returns the interfaces introduced by this advisor.
+
+The `validateInterfaces()` method is used internally to see whether or not the
+introduced interfaces can be implemented by the configured `IntroductionInterceptor`.
+
+Let's look at a simple example from the Spring test suite. Let's suppose we want to
+introduce the following interface to one or more objects:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public interface Lockable {
+ void lock();
+ void unlock();
+ boolean locked();
+ }
+----
+
+This illustrates a __mixin__. We want to be able to cast advised objects to Lockable,
+whatever their type, and call lock and unlock methods. If we call the lock() method, we
+want all setter methods to throw a `LockedException`. Thus we can add an aspect that
+provides the ability to make objects immutable, without them having any knowledge of it:
+a good example of AOP.
+
+Firstly, we'll need an `IntroductionInterceptor` that does the heavy lifting. In this
+case, we extend the `org.springframework.aop.support.DelegatingIntroductionInterceptor`
+convenience class. We could implement IntroductionInterceptor directly, but using
+`DelegatingIntroductionInterceptor` is best for most cases.
+
+The `DelegatingIntroductionInterceptor` is designed to delegate an introduction to an
+actual implementation of the introduced interface(s), concealing the use of interception
+to do so. The delegate can be set to any object using a constructor argument; the
+default delegate (when the no-arg constructor is used) is this. Thus in the example
+below, the delegate is the `LockMixin` subclass of `DelegatingIntroductionInterceptor`.
+Given a delegate (by default itself), a `DelegatingIntroductionInterceptor` instance
+looks for all interfaces implemented by the delegate (other than
+IntroductionInterceptor), and will support introductions against any of them. It's
+possible for subclasses such as `LockMixin` to call the `suppressInterface(Class intf)`
+method to suppress interfaces that should not be exposed. However, no matter how many
+interfaces an `IntroductionInterceptor` is prepared to support, the
+`IntroductionAdvisor` used will control which interfaces are actually exposed. An
+introduced interface will conceal any implementation of the same interface by the target.
+
+Thus `LockMixin` extends `DelegatingIntroductionInterceptor` and implements `Lockable`
+itself. The superclass automatically picks up that Lockable can be supported for
+introduction, so we don't need to specify that. We could introduce any number of
+interfaces in this way.
+
+Note the use of the `locked` instance variable. This effectively adds additional state
+to that held in the target object.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class LockMixin extends DelegatingIntroductionInterceptor implements Lockable {
+
+ private boolean locked;
+
+ public void lock() {
+ this.locked = true;
+ }
+
+ public void unlock() {
+ this.locked = false;
+ }
+
+ public boolean locked() {
+ return this.locked;
+ }
+
+ public Object invoke(MethodInvocation invocation) throws Throwable {
+ if (locked() && invocation.getMethod().getName().indexOf("set") == 0) {
+ throw new LockedException();
+ }
+ return super.invoke(invocation);
+ }
+
+ }
+----
+
+Often it isn't necessary to override the `invoke()` method: the
+`DelegatingIntroductionInterceptor` implementation - which calls the delegate method if
+the method is introduced, otherwise proceeds towards the join point - is usually
+sufficient. In the present case, we need to add a check: no setter method can be invoked
+if in locked mode.
+
+The introduction advisor required is simple. All it needs to do is hold a distinct
+`LockMixin` instance, and specify the introduced interfaces - in this case, just
+`Lockable`. A more complex example might take a reference to the introduction
+interceptor (which would be defined as a prototype): in this case, there's no
+configuration relevant for a `LockMixin`, so we simply create it using `new`.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class LockMixinAdvisor extends DefaultIntroductionAdvisor {
+
+ public LockMixinAdvisor() {
+ super(new LockMixin(), Lockable.class);
+ }
+ }
+----
+
+We can apply this advisor very simply: it requires no configuration. (However, it __is__
+necessary: It's impossible to use an `IntroductionInterceptor` without an
+__IntroductionAdvisor__.) As usual with introductions, the advisor must be per-instance,
+as it is stateful. We need a different instance of `LockMixinAdvisor`, and hence
+`LockMixin`, for each advised object. The advisor comprises part of the advised object's
+state.
+
+We can apply this advisor programmatically, using the `Advised.addAdvisor()` method, or
+(the recommended way) in XML configuration, like any other advisor. All proxy creation
+choices discussed below, including "auto proxy creators," correctly handle introductions
+and stateful mixins.
+
+
+
+
+[[aop-api-advisor]]
+=== Advisor API in Spring
+In Spring, an Advisor is an aspect that contains just a single advice object associated
+with a pointcut expression.
+
+Apart from the special case of introductions, any advisor can be used with any advice.
+`org.springframework.aop.support.DefaultPointcutAdvisor` is the most commonly used
+advisor class. For example, it can be used with a `MethodInterceptor`, `BeforeAdvice` or
+`ThrowsAdvice`.
+
+It is possible to mix advisor and advice types in Spring in the same AOP proxy. For
+example, you could use a interception around advice, throws advice and before advice in
+one proxy configuration: Spring will automatically create the necessary interceptor
+chain.
+
+
+
+
+[[aop-pfb]]
+=== Using the ProxyFactoryBean to create AOP proxies
+If you're using the Spring IoC container (an ApplicationContext or BeanFactory) for your
+business objects - and you should be! - you will want to use one of Spring's AOP
+FactoryBeans. (Remember that a factory bean introduces a layer of indirection, enabling
+it to create objects of a different type.)
+
+[NOTE]
+====
+The Spring AOP support also uses factory beans under the covers.
+====
+
+The basic way to create an AOP proxy in Spring is to use the
+__org.springframework.aop.framework.ProxyFactoryBean__. This gives complete control over
+the pointcuts and advice that will apply, and their ordering. However, there are simpler
+options that are preferable if you don't need such control.
+
+
+
+[[aop-pfb-1]]
+==== Basics
+The `ProxyFactoryBean`, like other Spring `FactoryBean` implementations, introduces a
+level of indirection. If you define a `ProxyFactoryBean` with name `foo`, what objects
+referencing `foo` see is not the `ProxyFactoryBean` instance itself, but an object
+created by the `ProxyFactoryBean`'s implementation of the `getObject()` method. This
+method will create an AOP proxy wrapping a target object.
+
+One of the most important benefits of using a `ProxyFactoryBean` or another IoC-aware
+class to create AOP proxies, is that it means that advices and pointcuts can also be
+managed by IoC. This is a powerful feature, enabling certain approaches that are hard to
+achieve with other AOP frameworks. For example, an advice may itself reference
+application objects (besides the target, which should be available in any AOP
+framework), benefiting from all the pluggability provided by Dependency Injection.
+
+
+
+[[aop-pfb-2]]
+==== JavaBean properties
+In common with most `FactoryBean` implementations provided with Spring, the
+`ProxyFactoryBean` class is itself a JavaBean. Its properties are used to:
+
+* Specify the target you want to proxy.
+* Specify whether to use CGLIB (see below and also <>).
+
+Some key properties are inherited from `org.springframework.aop.framework.ProxyConfig`
+(the superclass for all AOP proxy factories in Spring). These key properties include:
+
+* `proxyTargetClass`: `true` if the target class is to be proxied, rather than the
+ target class' interfaces. If this property value is set to `true`, then CGLIB proxies
+ will be created (but see also <>).
+* `optimize`: controls whether or not aggressive optimizations are applied to proxies
+ __created via CGLIB__. One should not blithely use this setting unless one fully
+ understands how the relevant AOP proxy handles optimization. This is currently used
+ only for CGLIB proxies; it has no effect with JDK dynamic proxies.
+* `frozen`: if a proxy configuration is `frozen`, then changes to the configuration are
+ no longer allowed. This is useful both as a slight optimization and for those cases
+ when you don't want callers to be able to manipulate the proxy (via the `Advised`
+ interface) after the proxy has been created. The default value of this property is
+ `false`, so changes such as adding additional advice are allowed.
+* `exposeProxy`: determines whether or not the current proxy should be exposed in a
+ `ThreadLocal` so that it can be accessed by the target. If a target needs to obtain
+ the proxy and the `exposeProxy` property is set to `true`, the target can use the
+ `AopContext.currentProxy()` method.
+
+Other properties specific to `ProxyFactoryBean` include:
+
+* `proxyInterfaces`: array of String interface names. If this isn't supplied, a CGLIB
+ proxy for the target class will be used (but see also <>).
+* `interceptorNames`: String array of `Advisor`, interceptor or other advice names to
+ apply. Ordering is significant, on a first come-first served basis. That is to say
+ that the first interceptor in the list will be the first to be able to intercept the
+ invocation.
+
+The names are bean names in the current factory, including bean names from ancestor
+factories. You can't mention bean references here since doing so would result in the
+`ProxyFactoryBean` ignoring the singleton setting of the advice.
+
+You can append an interceptor name with an asterisk ( `*`). This will result in the
+application of all advisor beans with names starting with the part before the asterisk
+to be applied. An example of using this feature can be found in <>.
+
+* singleton: whether or not the factory should return a single object, no matter how
+ often the `getObject()` method is called. Several `FactoryBean` implementations offer
+ such a method. The default value is `true`. If you want to use stateful advice - for
+ example, for stateful mixins - use prototype advices along with a singleton value of
+ `false`.
+
+
+
+[[aop-pfb-proxy-types]]
+==== JDK- and CGLIB-based proxies
+This section serves as the definitive documentation on how the `ProxyFactoryBean`
+chooses to create one of either a JDK- and CGLIB-based proxy for a particular target
+object (that is to be proxied).
+
+[NOTE]
+====
+The behavior of the `ProxyFactoryBean` with regard to creating JDK- or CGLIB-based
+proxies changed between versions 1.2.x and 2.0 of Spring. The `ProxyFactoryBean` now
+exhibits similar semantics with regard to auto-detecting interfaces as those of the
+`TransactionProxyFactoryBean` class.
+====
+
+If the class of a target object that is to be proxied (hereafter simply referred to as
+the target class) doesn't implement any interfaces, then a CGLIB-based proxy will be
+created. This is the easiest scenario, because JDK proxies are interface based, and no
+interfaces means JDK proxying isn't even possible. One simply plugs in the target bean,
+and specifies the list of interceptors via the `interceptorNames` property. Note that a
+CGLIB-based proxy will be created even if the `proxyTargetClass` property of the
+`ProxyFactoryBean` has been set to `false`. (Obviously this makes no sense, and is best
+removed from the bean definition because it is at best redundant, and at worst
+confusing.)
+
+If the target class implements one (or more) interfaces, then the type of proxy that is
+created depends on the configuration of the `ProxyFactoryBean`.
+
+If the `proxyTargetClass` property of the `ProxyFactoryBean` has been set to `true`,
+then a CGLIB-based proxy will be created. This makes sense, and is in keeping with the
+principle of least surprise. Even if the `proxyInterfaces` property of the
+`ProxyFactoryBean` has been set to one or more fully qualified interface names, the fact
+that the `proxyTargetClass` property is set to `true` __will__ cause CGLIB-based
+proxying to be in effect.
+
+If the `proxyInterfaces` property of the `ProxyFactoryBean` has been set to one or more
+fully qualified interface names, then a JDK-based proxy will be created. The created
+proxy will implement all of the interfaces that were specified in the `proxyInterfaces`
+property; if the target class happens to implement a whole lot more interfaces than
+those specified in the `proxyInterfaces` property, that is all well and good but those
+additional interfaces will not be implemented by the returned proxy.
+
+If the `proxyInterfaces` property of the `ProxyFactoryBean` has __not__ been set, but
+the target class __does implement one (or more)__ interfaces, then the
+`ProxyFactoryBean` will auto-detect the fact that the target class does actually
+implement at least one interface, and a JDK-based proxy will be created. The interfaces
+that are actually proxied will be __all__ of the interfaces that the target class
+implements; in effect, this is the same as simply supplying a list of each and every
+interface that the target class implements to the `proxyInterfaces` property. However,
+it is significantly less work, and less prone to typos.
+
+
+
+[[aop-api-proxying-intf]]
+==== Proxying interfaces
+Let's look at a simple example of `ProxyFactoryBean` in action. This example involves:
+
+* A __target bean__ that will be proxied. This is the "personTarget" bean definition in
+ the example below.
+* An Advisor and an Interceptor used to provide advice.
+* An AOP proxy bean definition specifying the target object (the personTarget bean) and
+ the interfaces to proxy, along with the advices to apply.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ myAdvisor
+ debugInterceptor
+
+
+
+----
+
+Note that the `interceptorNames` property takes a list of String: the bean names of the
+interceptor or advisors in the current factory. Advisors, interceptors, before, after
+returning and throws advice objects can be used. The ordering of advisors is significant.
+
+[NOTE]
+====
+You might be wondering why the list doesn't hold bean references. The reason for this is
+that if the ProxyFactoryBean's singleton property is set to false, it must be able to
+return independent proxy instances. If any of the advisors is itself a prototype, an
+independent instance would need to be returned, so it's necessary to be able to obtain
+an instance of the prototype from the factory; holding a reference isn't sufficient.
+====
+
+The "person" bean definition above can be used in place of a Person implementation, as
+follows:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ Person person = (Person) factory.getBean("person");
+----
+
+Other beans in the same IoC context can express a strongly typed dependency on it, as
+with an ordinary Java object:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+----
+
+The `PersonUser` class in this example would expose a property of type Person. As far as
+it's concerned, the AOP proxy can be used transparently in place of a "real" person
+implementation. However, its class would be a dynamic proxy class. It would be possible
+to cast it to the `Advised` interface (discussed below).
+
+It's possible to conceal the distinction between target and proxy using an anonymous
+__inner bean__, as follows. Only the `ProxyFactoryBean` definition is different; the
+advice is included only for completeness:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ myAdvisor
+ debugInterceptor
+
+
+
+----
+
+This has the advantage that there's only one object of type `Person`: useful if we want
+to prevent users of the application context from obtaining a reference to the un-advised
+object, or need to avoid any ambiguity with Spring IoC __autowiring__. There's also
+arguably an advantage in that the ProxyFactoryBean definition is self-contained.
+However, there are times when being able to obtain the un-advised target from the
+factory might actually be an __advantage__: for example, in certain test scenarios.
+
+
+
+[[aop-api-proxying-class]]
+==== Proxying classes
+What if you need to proxy a class, rather than one or more interfaces?
+
+Imagine that in our example above, there was no `Person` interface: we needed to advise
+a class called `Person` that didn't implement any business interface. In this case, you
+can configure Spring to use CGLIB proxying, rather than dynamic proxies. Simply set the
+`proxyTargetClass` property on the ProxyFactoryBean above to true. While it's best to
+program to interfaces, rather than classes, the ability to advise classes that don't
+implement interfaces can be useful when working with legacy code. (In general, Spring
+isn't prescriptive. While it makes it easy to apply good practices, it avoids forcing a
+particular approach.)
+
+If you want to, you can force the use of CGLIB in any case, even if you do have
+interfaces.
+
+CGLIB proxying works by generating a subclass of the target class at runtime. Spring
+configures this generated subclass to delegate method calls to the original target: the
+subclass is used to implement the __Decorator__ pattern, weaving in the advice.
+
+CGLIB proxying should generally be transparent to users. However, there are some issues
+to consider:
+
+* `Final` methods can't be advised, as they can't be overridden.
+* There is no need to add CGLIB to your classpath. As of Spring 3.2, CGLIB is repackaged
+ and included in the spring-core JAR. In other words, CGLIB-based AOP will work "out of
+ the box" just as do JDK dynamic proxies.
+
+There's little performance difference between CGLIB proxying and dynamic proxies. As of
+Spring 1.0, dynamic proxies are slightly faster. However, this may change in the future.
+Performance should not be a decisive consideration in this case.
+
+
+
+[[aop-global-advisors]]
+==== Using 'global' advisors
+By appending an asterisk to an interceptor name, all advisors with bean names matching
+the part before the asterisk, will be added to the advisor chain. This can come in handy
+if you need to add a standard set of 'global' advisors:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+ global*
+
+
+
+
+
+
+----
+
+
+
+
+[[aop-concise-proxy]]
+=== Concise proxy definitions
+Especially when defining transactional proxies, you may end up with many similar proxy
+definitions. The use of parent and child bean definitions, along with inner bean
+definitions, can result in much cleaner and more concise proxy definitions.
+
+First a parent, __template__, bean definition is created for the proxy:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+ PROPAGATION_REQUIRED
+
+
+
+----
+
+This will never be instantiated itself, so may actually be incomplete. Then each proxy
+which needs to be created is just a child bean definition, which wraps the target of the
+proxy as an inner bean definition, since the target will never be used on its own anyway.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+----
+
+It is of course possible to override properties from the parent template, such as in
+this case, the transaction propagation settings:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+ PROPAGATION_REQUIRED,readOnly
+ PROPAGATION_REQUIRED,readOnly
+ PROPAGATION_REQUIRED,readOnly
+ PROPAGATION_REQUIRED
+
+
+
+----
+
+Note that in the example above, we have explicitly marked the parent bean definition as
+__abstract__ by using the __abstract__ attribute, as described
+<>, so that it may not actually ever be
+instantiated. Application contexts (but not simple bean factories) will by default
+pre-instantiate all singletons. It is therefore 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 try to
+pre-instantiate it.
+
+
+
+
+[[aop-prog]]
+=== Creating AOP proxies programmatically with the ProxyFactory
+It's easy to create AOP proxies programmatically using Spring. This enables you to use
+Spring AOP without dependency on Spring IoC.
+
+The following listing shows creation of a proxy for a target object, with one
+interceptor and one advisor. The interfaces implemented by the target object will
+automatically be proxied:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ ProxyFactory factory = new ProxyFactory(myBusinessInterfaceImpl);
+ factory.addAdvice(myMethodInterceptor);
+ factory.addAdvisor(myAdvisor);
+ MyBusinessInterface tb = (MyBusinessInterface) factory.getProxy();
+----
+
+The first step is to construct an object of type
+`org.springframework.aop.framework.ProxyFactory`. You can create this with a target
+object, as in the above example, or specify the interfaces to be proxied in an alternate
+constructor.
+
+You can add advices (with interceptors as a specialized kind of advice) and/or advisors,
+and manipulate them for the life of the ProxyFactory. If you add an
+IntroductionInterceptionAroundAdvisor, you can cause the proxy to implement additional
+interfaces.
+
+There are also convenience methods on ProxyFactory (inherited from `AdvisedSupport`)
+which allow you to add other advice types such as before and throws advice.
+AdvisedSupport is the superclass of both ProxyFactory and ProxyFactoryBean.
+
+[TIP]
+====
+
+Integrating AOP proxy creation with the IoC framework is best practice in most
+applications. We recommend that you externalize configuration from Java code with AOP,
+as in general.
+====
+
+
+
+
+[[aop-api-advised]]
+=== Manipulating advised objects
+However you create AOP proxies, you can manipulate them using the
+`org.springframework.aop.framework.Advised` interface. Any AOP proxy can be cast to this
+interface, whichever other interfaces it implements. This interface includes the
+following methods:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ Advisor[] getAdvisors();
+
+ void addAdvice(Advice advice) throws AopConfigException;
+
+ void addAdvice(int pos, Advice advice) throws AopConfigException;
+
+ void addAdvisor(Advisor advisor) throws AopConfigException;
+
+ void addAdvisor(int pos, Advisor advisor) throws AopConfigException;
+
+ int indexOf(Advisor advisor);
+
+ boolean removeAdvisor(Advisor advisor) throws AopConfigException;
+
+ void removeAdvisor(int index) throws AopConfigException;
+
+ boolean replaceAdvisor(Advisor a, Advisor b) throws AopConfigException;
+
+ boolean isFrozen();
+----
+
+The `getAdvisors()` method will return an Advisor for every advisor, interceptor or
+other advice type that has been added to the factory. If you added an Advisor, the
+returned advisor at this index will be the object that you added. If you added an
+interceptor or other advice type, Spring will have wrapped this in an advisor with a
+pointcut that always returns true. Thus if you added a `MethodInterceptor`, the advisor
+returned for this index will be an `DefaultPointcutAdvisor` returning your
+`MethodInterceptor` and a pointcut that matches all classes and methods.
+
+The `addAdvisor()` methods can be used to add any Advisor. Usually the advisor holding
+pointcut and advice will be the generic `DefaultPointcutAdvisor`, which can be used with
+any advice or pointcut (but not for introductions).
+
+By default, it's possible to add or remove advisors or interceptors even once a proxy
+has been created. The only restriction is that it's impossible to add or remove an
+introduction advisor, as existing proxies from the factory will not show the interface
+change. (You can obtain a new proxy from the factory to avoid this problem.)
+
+A simple example of casting an AOP proxy to the `Advised` interface and examining and
+manipulating its advice:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ Advised advised = (Advised) myObject;
+ Advisor[] advisors = advised.getAdvisors();
+ int oldAdvisorCount = advisors.length;
+ System.out.println(oldAdvisorCount + " advisors");
+
+ // Add an advice like an interceptor without a pointcut
+ // Will match all proxied methods
+ // Can use for interceptors, before, after returning or throws advice
+ advised.addAdvice(new DebugInterceptor());
+
+ // Add selective advice using a pointcut
+ advised.addAdvisor(new DefaultPointcutAdvisor(mySpecialPointcut, myAdvice));
+
+ assertEquals("Added two advisors", oldAdvisorCount + 2, advised.getAdvisors().length);
+----
+
+[NOTE]
+====
+It's questionable whether it's advisable (no pun intended) to modify advice on a
+business object in production, although there are no doubt legitimate usage cases.
+However, it can be very useful in development: for example, in tests. I have sometimes
+found it very useful to be able to add test code in the form of an interceptor or other
+advice, getting inside a method invocation I want to test. (For example, the advice can
+get inside a transaction created for that method: for example, to run SQL to check that
+a database was correctly updated, before marking the transaction for roll back.)
+====
+
+Depending on how you created the proxy, you can usually set a `frozen` flag, in which
+case the `Advised` `isFrozen()` method will return true, and any attempts to modify
+advice through addition or removal will result in an `AopConfigException`. The ability
+to freeze the state of an advised object is useful in some cases, for example, to
+prevent calling code removing a security interceptor. It may also be used in Spring 1.1
+to allow aggressive optimization if runtime advice modification is known not to be
+required.
+
+
+
+
+[[aop-autoproxy]]
+=== Using the "auto-proxy" facility
+So far we've considered explicit creation of AOP proxies using a `ProxyFactoryBean` or
+similar factory bean.
+
+Spring also allows us to use "auto-proxy" bean definitions, which can automatically
+proxy selected bean definitions. This is built on Spring "bean post processor"
+infrastructure, which enables modification of any bean definition as the container loads.
+
+In this model, you set up some special bean definitions in your XML bean definition file
+to configure the auto proxy infrastructure. This allows you just to declare the targets
+eligible for auto-proxying: you don't need to use `ProxyFactoryBean`.
+
+There are two ways to do this:
+
+* Using an auto-proxy creator that refers to specific beans in the current context.
+* A special case of auto-proxy creation that deserves to be considered separately;
+ auto-proxy creation driven by source-level metadata attributes.
+
+
+
+[[aop-autoproxy-choices]]
+==== Autoproxy bean definitions
+The `org.springframework.aop.framework.autoproxy` package provides the following
+standard auto-proxy creators.
+
+
+[[aop-api-autoproxy]]
+===== BeanNameAutoProxyCreator
+The `BeanNameAutoProxyCreator` class is a `BeanPostProcessor` that automatically creates
+AOP proxies for beans with names matching literal values or wildcards.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+ myInterceptor
+
+
+
+----
+
+As with `ProxyFactoryBean`, there is an `interceptorNames` property rather than a list
+of interceptors, to allow correct behavior for prototype advisors. Named "interceptors"
+can be advisors or any advice type.
+
+As with auto proxying in general, the main point of using `BeanNameAutoProxyCreator` is
+to apply the same configuration consistently to multiple objects, with minimal volume of
+configuration. It is a popular choice for applying declarative transactions to multiple
+objects.
+
+Bean definitions whose names match, such as "jdkMyBean" and "onlyJdk" in the above
+example, are plain old bean definitions with the target class. An AOP proxy will be
+created automatically by the `BeanNameAutoProxyCreator`. The same advice will be applied
+to all matching beans. Note that if advisors are used (rather than the interceptor in
+the above example), the pointcuts may apply differently to different beans.
+
+
+[[aop-api-autoproxy-default]]
+===== DefaultAdvisorAutoProxyCreator
+A more general and extremely powerful auto proxy creator is
+`DefaultAdvisorAutoProxyCreator`. This will automagically apply eligible advisors in the
+current context, without the need to include specific bean names in the auto-proxy
+advisor's bean definition. It offers the same merit of consistent configuration and
+avoidance of duplication as `BeanNameAutoProxyCreator`.
+
+Using this mechanism involves:
+
+* Specifying a `DefaultAdvisorAutoProxyCreator` bean definition.
+* Specifying any number of Advisors in the same or related contexts. Note that these
+ __must__ be Advisors, not just interceptors or other advices. This is necessary
+ because there must be a pointcut to evaluate, to check the eligibility of each advice
+ to candidate bean definitions.
+
+The `DefaultAdvisorAutoProxyCreator` will automatically evaluate the pointcut contained
+in each advisor, to see what (if any) advice it should apply to each business object
+(such as "businessObject1" and "businessObject2" in the example).
+
+This means that any number of advisors can be applied automatically to each business
+object. If no pointcut in any of the advisors matches any method in a business object,
+the object will not be proxied. As bean definitions are added for new business objects,
+they will automatically be proxied if necessary.
+
+Autoproxying in general has the advantage of making it impossible for callers or
+dependencies to obtain an un-advised object. Calling getBean("businessObject1") on this
+ApplicationContext will return an AOP proxy, not the target business object. (The "inner
+bean" idiom shown earlier also offers this benefit.)
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+
+
+
+
+
+----
+
+The `DefaultAdvisorAutoProxyCreator` is very useful if you want to apply the same advice
+consistently to many business objects. Once the infrastructure definitions are in place,
+you can simply add new business objects without including specific proxy configuration.
+You can also drop in additional aspects very easily - for example, tracing or
+performance monitoring aspects - with minimal change to configuration.
+
+The DefaultAdvisorAutoProxyCreator offers support for filtering (using a naming
+convention so that only certain advisors are evaluated, allowing use of multiple,
+differently configured, AdvisorAutoProxyCreators in the same factory) and ordering.
+Advisors can implement the `org.springframework.core.Ordered` interface to ensure
+correct ordering if this is an issue. The TransactionAttributeSourceAdvisor used in the
+above example has a configurable order value; the default setting is unordered.
+
+
+[[aop-api-autoproxy-abstract]]
+===== AbstractAdvisorAutoProxyCreator
+This is the superclass of DefaultAdvisorAutoProxyCreator. You can create your own
+auto-proxy creators by subclassing this class, in the unlikely event that advisor
+definitions offer insufficient customization to the behavior of the framework
+`DefaultAdvisorAutoProxyCreator`.
+
+
+
+[[aop-autoproxy-metadata]]
+==== Using metadata-driven auto-proxying
+A particularly important type of auto-proxying is driven by metadata. This produces a
+similar programming model to .NET `ServicedComponents`. Instead of defining metadata in
+XML descriptors, configuration for transaction management and other enterprise services
+is held in source-level attributes.
+
+In this case, you use the `DefaultAdvisorAutoProxyCreator`, in combination with Advisors
+that understand metadata attributes. The metadata specifics are held in the pointcut
+part of the candidate advisors, rather than in the auto-proxy creation class itself.
+
+This is really a special case of the `DefaultAdvisorAutoProxyCreator`, but deserves
+consideration on its own. (The metadata-aware code is in the pointcuts contained in the
+advisors, not the AOP framework itself.)
+
+The `/attributes` directory of the JPetStore sample application shows the use of
+attribute-driven auto-proxying. In this case, there's no need to use the
+`TransactionProxyFactoryBean`. Simply defining transactional attributes on business
+objects is sufficient, because of the use of metadata-aware pointcuts. The bean
+definitions include the following code, in `/WEB-INF/declarativeServices.xml`. Note that
+this is generic, and can be used outside the JPetStore:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+----
+
+The `DefaultAdvisorAutoProxyCreator` bean definition (the name is not significant, hence
+it can even be omitted) will pick up all eligible pointcuts in the current application
+context. In this case, the "transactionAdvisor" bean definition, of type
+`TransactionAttributeSourceAdvisor`, will apply to classes or methods carrying a
+transaction attribute. The TransactionAttributeSourceAdvisor depends on a
+TransactionInterceptor, via constructor dependency. The example resolves this via
+autowiring. The `AttributesTransactionAttributeSource` depends on an implementation of
+the `org.springframework.metadata.Attributes` interface. In this fragment, the
+"attributes" bean satisfies this, using the Jakarta Commons Attributes API to obtain
+attribute information. (The application code must have been compiled using the Commons
+Attributes compilation task.)
+
+The `/annotation` directory of the JPetStore sample application contains an analogous
+example for auto-proxying driven by JDK 1.5+ annotations. The following configuration
+enables automatic detection of Spring's `Transactional` annotation, leading to implicit
+proxies for beans containing that annotation:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+
+
+
+
+----
+
+The `TransactionInterceptor` defined here depends on a `PlatformTransactionManager`
+definition, which is not included in this generic file (although it could be) because it
+will be specific to the application's transaction requirements (typically JTA, as in
+this example, or Hibernate, JDO or JDBC):
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+----
+
+[TIP]
+====
+
+If you require only declarative transaction management, using these generic XML
+definitions will result in Spring automatically proxying all classes or methods with
+transaction attributes. You won't need to work directly with AOP, and the programming
+model is similar to that of .NET ServicedComponents.
+====
+
+This mechanism is extensible. It's possible to do auto-proxying based on custom
+attributes. You need to:
+
+* Define your custom attribute.
+* Specify an Advisor with the necessary advice, including a pointcut that is triggered
+ by the presence of the custom attribute on a class or method. You may be able to use
+ an existing advice, merely implementing a static pointcut that picks up the custom
+ attribute.
+
+It's possible for such advisors to be unique to each advised class (for example, mixins):
+they simply need to be defined as prototype, rather than singleton, bean definitions.
+For example, the `LockMixin` introduction interceptor from the Spring test suite,
+shown above, could be used in conjunction with a generic `DefaultIntroductionAdvisor`:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+----
+
+Note that both `lockMixin` and `lockableAdvisor` are defined as prototypes.
+
+
+
+
+[[aop-targetsource]]
+=== Using TargetSources
+Spring offers the concept of a __TargetSource__, expressed in the
+`org.springframework.aop.TargetSource` interface. This interface is responsible for
+returning the "target object" implementing the join point. The `TargetSource`
+implementation is asked for a target instance each time the AOP proxy handles a method
+invocation.
+
+Developers using Spring AOP don't normally need to work directly with TargetSources, but
+this provides a powerful means of supporting pooling, hot swappable and other
+sophisticated targets. For example, a pooling TargetSource can return a different target
+instance for each invocation, using a pool to manage instances.
+
+If you do not specify a TargetSource, a default implementation is used that wraps a
+local object. The same target is returned for each invocation (as you would expect).
+
+Let's look at the standard target sources provided with Spring, and how you can use them.
+
+[TIP]
+====
+
+When using a custom target source, your target will usually need to be a prototype
+rather than a singleton bean definition. This allows Spring to create a new target
+instance when required.
+====
+
+
+
+[[aop-ts-swap]]
+==== Hot swappable target sources
+The `org.springframework.aop.target.HotSwappableTargetSource` exists to allow the target
+of an AOP proxy to be switched while allowing callers to keep their references to it.
+
+Changing the target source's target takes effect immediately. The
+`HotSwappableTargetSource` is threadsafe.
+
+You can change the target via the `swap()` method on HotSwappableTargetSource as follows:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ HotSwappableTargetSource swapper = (HotSwappableTargetSource) beanFactory.getBean("swapper");
+ Object oldTarget = swapper.swap(newTarget);
+----
+
+The XML definitions required look as follows:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+
+----
+
+The above `swap()` call changes the target of the swappable bean. Clients who hold a
+reference to that bean will be unaware of the change, but will immediately start hitting
+the new target.
+
+Although this example doesn't add any advice - and it's not necessary to add advice to
+use a `TargetSource` - of course any `TargetSource` can be used in conjunction with
+arbitrary advice.
+
+
+
+[[aop-ts-pool]]
+==== Pooling target sources
+Using a pooling target source provides a similar programming model to stateless session
+EJBs, in which a pool of identical instances is maintained, with method invocations
+going to free objects in the pool.
+
+A crucial difference between Spring pooling and SLSB pooling is that Spring pooling can
+be applied to any POJO. As with Spring in general, this service can be applied in a
+non-invasive way.
+
+Spring provides out-of-the-box support for Jakarta Commons Pool 1.3, which provides a
+fairly efficient pooling implementation. You'll need the commons-pool Jar on your
+application's classpath to use this feature. It's also possible to subclass
+`org.springframework.aop.target.AbstractPoolingTargetSource` to support any other
+pooling API.
+
+Sample configuration is shown below:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+ ... properties omitted
+
+
+
+
+
+
+
+
+
+
+
+----
+
+Note that the target object - "businessObjectTarget" in the example - __must__ be a
+prototype. This allows the `PoolingTargetSource` implementation to create new instances
+of the target to grow the pool as necessary. See the javadocs of
+`AbstractPoolingTargetSource` and the concrete subclass you wish to use for information
+about its properties: "maxSize" is the most basic, and always guaranteed to be present.
+
+In this case, "myInterceptor" is the name of an interceptor that would need to be
+defined in the same IoC context. However, it isn't necessary to specify interceptors to
+use pooling. If you want only pooling, and no other advice, don't set the
+interceptorNames property at all.
+
+It's possible to configure Spring so as to be able to cast any pooled object to the
+`org.springframework.aop.target.PoolingConfig` interface, which exposes information
+about the configuration and current size of the pool through an introduction. You'll
+need to define an advisor like this:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+----
+
+This advisor is obtained by calling a convenience method on the
+`AbstractPoolingTargetSource` class, hence the use of MethodInvokingFactoryBean. This
+advisor's name ("poolConfigAdvisor" here) must be in the list of interceptors names in
+the ProxyFactoryBean exposing the pooled object.
+
+The cast will look as follows:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ PoolingConfig conf = (PoolingConfig) beanFactory.getBean("businessObject");
+ System.out.println("Max pool size is " + conf.getMaxSize());
+----
+
+[NOTE]
+====
+Pooling stateless service objects is not usually necessary. We don't believe it should
+be the default choice, as most stateless objects are naturally thread safe, and instance
+pooling is problematic if resources are cached.
+====
+
+Simpler pooling is available using auto-proxying. It's possible to set the TargetSources
+used by any auto-proxy creator.
+
+
+
+[[aop-ts-prototype]]
+==== Prototype target sources
+Setting up a "prototype" target source is similar to a pooling TargetSource. In this
+case, a new instance of the target will be created on every method invocation. Although
+the cost of creating a new object isn't high in a modern JVM, the cost of wiring up the
+new object (satisfying its IoC dependencies) may be more expensive. Thus you shouldn't
+use this approach without very good reason.
+
+To do this, you could modify the `poolTargetSource` definition shown above as follows.
+(I've also changed the name, for clarity.)
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+----
+
+There's only one property: the name of the target bean. Inheritance is used in the
+TargetSource implementations to ensure consistent naming. As with the pooling target
+source, the target bean must be a prototype bean definition.
+
+
+
+[[aop-ts-threadlocal]]
+==== ThreadLocal target sources
+
+`ThreadLocal` target sources are useful if you need an object to be created for each
+incoming request (per thread that is). The concept of a `ThreadLocal` provide a JDK-wide
+facility to transparently store resource alongside a thread. Setting up a
+`ThreadLocalTargetSource` is pretty much the same as was explained for the other types
+of target source:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+----
+
+[NOTE]
+====
+ThreadLocals come with serious issues (potentially resulting in memory leaks) when
+incorrectly using them in a multi-threaded and multi-classloader environments. One
+should always consider wrapping a threadlocal in some other class and never directly use
+the `ThreadLocal` itself (except of course in the wrapper class). Also, one should
+always remember to correctly set and unset (where the latter simply involved a call to
+`ThreadLocal.set(null)`) the resource local to the thread. Unsetting should be done in
+any case since not unsetting it might result in problematic behavior. Spring's
+ThreadLocal support does this for you and should always be considered in favor of using
+ThreadLocals without other proper handling code.
+====
+
+
+
+
+[[aop-extensibility]]
+=== Defining new Advice types
+
+Spring AOP is designed to be extensible. While the interception implementation strategy
+is presently used internally, it is possible to support arbitrary advice types in
+addition to the out-of-the-box interception around advice, before, throws advice and
+after returning advice.
+
+The `org.springframework.aop.framework.adapter` package is an SPI package allowing
+support for new custom advice types to be added without changing the core framework.
+The only constraint on a custom `Advice` type is that it must implement the
+`org.aopalliance.aop.Advice` marker interface.
+
+Please refer to the `org.springframework.aop.framework.adapter` javadocs for further
+information.
+
+
+
+
+[[aop-api-resources]]
+=== Further resources
+Please refer to the Spring sample applications for further examples of Spring AOP:
+
+* The JPetStore's default configuration illustrates the use of the
+ `TransactionProxyFactoryBean` for declarative transaction management.
+* The `/attributes` directory of the JPetStore illustrates the use of attribute-driven
+ declarative transaction management.
+
+
+
+
+
diff --git a/src/asciidoc/aop.adoc b/src/asciidoc/aop.adoc
new file mode 100644
index 000000000000..805f33bcb284
--- /dev/null
+++ b/src/asciidoc/aop.adoc
@@ -0,0 +1,3544 @@
+[[aop]]
+== Aspect Oriented Programming with Spring
+
+
+
+
+[[aop-introduction]]
+=== Introduction
+__Aspect-Oriented Programming__ (AOP) complements Object-Oriented Programming (OOP) by
+providing another way of thinking about program structure. The key unit of modularity in
+OOP is the class, whereas in AOP the unit of modularity is the __aspect__. Aspects
+enable the modularization of concerns such as transaction management that cut across
+multiple types and objects. (Such concerns are often termed __crosscutting__ concerns in
+AOP literature.)
+
+One of the key components of Spring is the __AOP framework__. While the Spring IoC
+container does not depend on AOP, meaning you do not need to use AOP if you don't want
+to, AOP complements Spring IoC to provide a very capable middleware solution.
+
+.Spring 2.0 AOP
+****
+Spring 2.0 introduces a simpler and more powerful way of writing custom aspects using
+either a <> or the <>. Both of these styles offer fully typed advice and use of the AspectJ pointcut
+language, while still using Spring AOP for weaving.
+
+The Spring 2.0 schema- and @AspectJ-based AOP support is discussed in this chapter.
+Spring 2.0 AOP remains fully backwards compatible with Spring 1.2 AOP, and the
+lower-level AOP support offered by the Spring 1.2 APIs is discussed in <>.
+****
+
+AOP is used in the Spring Framework to...
+
+* ... provide declarative enterprise services, especially as a replacement for EJB
+ declarative services. The most important such service is
+ <>.
+* ... 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.
+====
+
+
+
+[[aop-introduction-defn]]
+==== AOP concepts
+Let us begin by defining some central AOP concepts and terminology. These terms are not
+Spring-specific... unfortunately, AOP terminology is not particularly intuitive;
+however, it would be even more confusing if Spring used its own terminology.
+
+* __Aspect__: a modularization of a concern that cuts across multiple classes.
+ Transaction management is a good example of a crosscutting concern in enterprise Java
+ applications. In Spring AOP, aspects are implemented using regular classes
+ (the <>) or regular classes annotated with the
+ `@Aspect` annotation (the <>).
+* __Join point__: a point during the execution of a program, such as the execution of a
+ method or the handling of an exception. In Spring AOP, a join point __always__
+ represents a method execution.
+* __Advice__: action taken by an aspect at a particular join point. Different types of
+ advice include "around," "before" and "after" advice. (Advice types are discussed
+ below.) Many AOP frameworks, including Spring, model an advice as an __interceptor__,
+ maintaining a chain of interceptors __around__ the join point.
+* __Pointcut__: a predicate that matches join points. Advice is associated with a
+ pointcut expression and runs at any join point matched by the pointcut (for example,
+ the execution of a method with a certain name). The concept of join points as matched
+ by pointcut expressions is central to AOP, and Spring uses the AspectJ pointcut
+ expression language by default.
+* __Introduction__: declaring additional methods or fields on behalf of a type. Spring
+ AOP allows you to introduce new interfaces (and a corresponding implementation) to any
+ advised object. For example, you could use an introduction to make a bean implement an
+ `IsModified` interface, to simplify caching. (An introduction is known as an
+ inter-type declaration in the AspectJ community.)
+* __Target object__: object being advised by one or more aspects. Also referred to as
+ the __advised__ object. Since Spring AOP is implemented using runtime proxies, this
+ object will always be a __proxied__ object.
+* __AOP proxy__: an object created by the AOP framework in order to implement the aspect
+ contracts (advise method executions and so on). In the Spring Framework, an AOP proxy
+ will be a JDK dynamic proxy or a CGLIB proxy.
+* __Weaving__: linking aspects with other application types or objects to create an
+ advised object. This can be done at compile time (using the AspectJ compiler, for
+ example), load time, or at runtime. Spring AOP, like other pure Java AOP frameworks,
+ performs weaving at runtime.
+
+Types of advice:
+
+* __Before advice__: Advice that executes before a join point, but which does not have
+ the ability to prevent execution flow proceeding to the join point (unless it throws
+ an exception).
+* __After returning advice__: Advice to be executed after a join point completes
+ normally: for example, if a method returns without throwing an exception.
+* __After throwing advice__: Advice to be executed if a method exits by throwing an
+ exception.
+* __After (finally) advice__: Advice to be executed regardless of the means by which a
+ join point exits (normal or exceptional return).
+* __Around advice__: Advice that surrounds a join point such as a method invocation.
+ This is the most powerful kind of advice. Around advice can perform custom behavior
+ before and after the method invocation. It is also responsible for choosing whether to
+ proceed to the join point or to shortcut the advised method execution by returning its
+ own return value or throwing an exception.
+
+Around advice is the most general kind of advice. Since Spring AOP, like AspectJ,
+provides a full range of advice types, we recommend that you use the least powerful
+advice type that can implement the required behavior. For example, if you need only to
+update a cache with the return value of a method, you are better off implementing an
+after returning advice than an around advice, although an around advice can accomplish
+the same thing. Using the most specific advice type provides a simpler programming model
+with less potential for errors. For example, you do not need to invoke the `proceed()`
+method on the `JoinPoint` used for around advice, and hence cannot fail to invoke it.
+
+In Spring 2.0, all advice parameters are statically typed, so that you work with advice
+parameters of the appropriate type (the type of the return value from a method execution
+for example) rather than `Object` arrays.
+
+The concept of join points, matched by pointcuts, is the key to AOP which distinguishes
+it from older technologies offering only interception. Pointcuts enable advice to be
+targeted independently of the Object-Oriented hierarchy. For example, an around advice
+providing declarative transaction management can be applied to a set of methods spanning
+multiple objects (such as all business operations in the service layer).
+
+
+
+[[aop-introduction-spring-defn]]
+==== Spring AOP capabilities and goals
+Spring AOP is implemented in pure Java. There is no need for a special compilation
+process. Spring AOP does not need to control the class loader hierarchy, and is thus
+suitable for use in a Servlet container or application server.
+
+Spring AOP currently supports only method execution join points (advising the execution
+of methods on Spring beans). Field interception is not implemented, although support for
+field interception could be added without breaking the core Spring AOP APIs. If you need
+to advise field access and update join points, consider a language such as AspectJ.
+
+Spring AOP's approach to AOP differs from that of most other AOP frameworks. The aim is
+not to provide the most complete AOP implementation (although Spring AOP is quite
+capable); it is rather to provide a close integration between AOP implementation and
+Spring IoC to help solve common problems in enterprise applications.
+
+Thus, for example, the Spring Framework's AOP functionality is normally used in
+conjunction with the Spring IoC container. Aspects are configured using normal bean
+definition syntax (although this allows powerful "autoproxying" capabilities): this is a
+crucial difference from other AOP implementations. There are some things you cannot do
+easily or efficiently with Spring AOP, such as advise very fine-grained objects (such as
+domain objects typically): AspectJ is the best choice in such cases. However, our
+experience is that Spring AOP provides an excellent solution to most problems in
+enterprise Java applications that are amenable to AOP.
+
+Spring AOP will never strive to compete with AspectJ to provide a comprehensive AOP
+solution. We believe that both proxy-based frameworks like Spring AOP and full-blown
+frameworks such as AspectJ are valuable, and that they are complementary, rather than in
+competition. Spring seamlessly integrates Spring AOP and IoC with AspectJ, to enable
+all uses of AOP to be catered for within a consistent Spring-based application
+architecture. This integration does not affect the Spring AOP API or the AOP Alliance
+API: Spring AOP remains backward-compatible. See <> for a
+discussion of the Spring AOP APIs.
+
+[NOTE]
+====
+One of the central tenets of the Spring Framework is that of __non-invasiveness__; this
+is the idea that you should not be forced to introduce framework-specific classes and
+interfaces into your business/domain model. However, in some places the Spring Framework
+does give you the option to introduce Spring Framework-specific dependencies into your
+codebase: the rationale in giving you such options is because in certain scenarios it
+might be just plain easier to read or code some specific piece of functionality in such
+a way. The Spring Framework (almost) always offers you the choice though: you have the
+freedom to make an informed decision as to which option best suits your particular use
+case or scenario.
+
+One such choice that is relevant to this chapter is that of which AOP framework (and
+which AOP style) to choose. You have the choice of AspectJ and/or Spring AOP, and you
+also have the choice of either the @AspectJ annotation-style approach or the Spring XML
+configuration-style approach. The fact that this chapter chooses to introduce the
+@AspectJ-style approach first should not be taken as an indication that the Spring team
+favors the @AspectJ annotation-style approach over the Spring XML configuration-style.
+
+See <> for a more complete discussion of the whys and wherefores of each
+style.
+====
+
+
+
+[[aop-introduction-proxies]]
+==== AOP Proxies
+Spring AOP defaults to using standard JDK __dynamic proxies__ for AOP proxies. This
+enables any interface (or set of interfaces) to be proxied.
+
+Spring AOP can also use CGLIB proxies. This is necessary to proxy classes, rather than
+interfaces. CGLIB is used by default if a business object does not implement an
+interface. As it is good practice to program to interfaces rather than classes, business
+classes normally will implement one or more business interfaces. It is possible to
+<>, in those (hopefully rare) cases
+where you need to advise a method that is not declared on an interface, or where you
+need to pass a proxied object to a method as a concrete type.
+
+It is important to grasp the fact that Spring AOP is __proxy-based__. See
+<> for a thorough examination of exactly what this
+implementation detail actually means.
+
+
+
+
+[[aop-ataspectj]]
+=== @AspectJ support
+@AspectJ refers to a style of declaring aspects as regular Java classes annotated with
+annotations. The @AspectJ style was introduced by the
+http://www.eclipse.org/aspectj[AspectJ project] as part of the AspectJ 5 release. Spring
+interprets the same annotations as AspectJ 5, using a library supplied by AspectJ
+for pointcut parsing and matching. The AOP runtime is still pure Spring AOP though, and
+there is no dependency on the AspectJ compiler or weaver.
+
+[NOTE]
+====
+Using the AspectJ compiler and weaver enables use of the full AspectJ language, and is
+discussed in <>.
+====
+
+
+
+[[aop-aspectj-support]]
+==== Enabling @AspectJ Support
+To use @AspectJ aspects in a Spring configuration you need to enable Spring support for
+configuring Spring AOP based on @AspectJ aspects, and __autoproxying__ beans based on
+whether or not they are advised by those aspects. By autoproxying we mean that if Spring
+determines that a bean is advised by one or more aspects, it will automatically generate
+a proxy for that bean to intercept method invocations and ensure that advice is executed
+as needed.
+
+The @AspectJ support can be enabled with XML or Java style configuration. In either
+case you will also need to ensure that AspectJ's `aspectjweaver.jar` library is on the
+classpath of your application (version 1.6.8 or later). This library is available in the
+`'lib'` directory of an AspectJ distribution or via the Maven Central repository.
+
+
+[[aop-enable-aspectj-java]]
+===== Enabling @AspectJ Support with Java configuration
+To enable @AspectJ support with Java `@Configuration` add the `@EnableAspectJAutoProxy`
+annotation:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Configuration
+ @EnableAspectJAutoProxy
+ public class AppConfig {
+
+ }
+----
+
+
+[[aop-enable-aspectj-xml]]
+===== Enabling @AspectJ Support with XML configuration
+To enable @AspectJ support with XML based configuration use the `aop:aspectj-autoproxy`
+element:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+----
+
+This assumes that you are using schema support as described in <>. See
+<> for how to import the tags in the aop namespace.
+
+
+
+[[aop-at-aspectj]]
+==== Declaring an aspect
+
+With the @AspectJ support enabled, any bean defined in your application context with a
+class that is an @AspectJ aspect (has the `@Aspect` annotation) will be automatically
+detected by Spring and used to configure Spring AOP. The following example shows the
+minimal definition required for a not-very-useful aspect:
+
+A regular bean definition in the application context, pointing to a bean class that has
+the `@Aspect` annotation:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+----
+
+And the `NotVeryUsefulAspect` class definition, annotated with
+`org.aspectj.lang.annotation.Aspect` annotation;
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ package org.xyz;
+ import org.aspectj.lang.annotation.Aspect;
+
+ @Aspect
+ public class NotVeryUsefulAspect {
+
+ }
+----
+
+Aspects (classes annotated with `@Aspect`) may have methods and fields just like any
+other class. They may also contain pointcut, advice, and introduction (inter-type)
+declarations.
+
+.Autodetecting aspects through component scanning
+[NOTE]
+====
+You may register aspect classes as regular beans in your Spring XML configuration, or
+autodetect them through classpath scanning - just like any other Spring-managed bean.
+However, note that the __@Aspect__ annotation is __not__ sufficient for autodetection in
+the classpath: For that purpose, you need to add a separate __@Component__ annotation
+(or alternatively a custom stereotype annotation that qualifies, as per the rules of
+Spring's component scanner).
+====
+
+.Advising aspects with other aspects?
+[NOTE]
+====
+In Spring AOP, it is __not__ possible to have aspects themselves be the target of advice
+from other aspects. The __@Aspect__ annotation on a class marks it as an aspect, and
+hence excludes it from auto-proxying.
+====
+
+
+
+[[aop-pointcuts]]
+==== Declaring a pointcut
+Recall that pointcuts determine join points of interest, and thus enable us to control
+when advice executes. __Spring AOP only supports method execution join points for Spring
+beans__, so you can think of a pointcut as matching the execution of methods on Spring
+beans. A pointcut declaration has two parts: a signature comprising a name and any
+parameters, and a pointcut expression that determines __exactly__ which method
+executions we are interested in. In the @AspectJ annotation-style of AOP, a pointcut
+signature is provided by a regular method definition, and the pointcut expression is
+indicated using the `@Pointcut` annotation (the method serving as the pointcut signature
+__must__ have a `void` return type).
+
+An example will help make this distinction between a pointcut signature and a pointcut
+expression clear. The following example defines a pointcut named `'anyOldTransfer'` that
+will match the execution of any method named `'transfer'`:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Pointcut("execution(* transfer(..))")// the pointcut expression
+ private void anyOldTransfer() {}// the pointcut signature
+----
+
+The pointcut expression that forms the value of the `@Pointcut` annotation is a regular
+AspectJ 5 pointcut expression. For a full discussion of AspectJ's pointcut language, see
+the http://www.eclipse.org/aspectj/doc/released/progguide/index.html[AspectJ
+Programming Guide] (and for extensions, the
+http://www.eclipse.org/aspectj/doc/released/adk15notebook/index.html[AspectJ 5
+Developers Notebook]) or one of the books on AspectJ such as "Eclipse AspectJ" by Colyer
+et. al. or "AspectJ in Action" by Ramnivas Laddad.
+
+
+[[aop-pointcuts-designators]]
+===== Supported Pointcut Designators
+Spring AOP supports the following AspectJ pointcut designators (PCD) for use in pointcut
+expressions:
+
+.Other pointcut types
+****
+The full AspectJ pointcut language supports additional pointcut designators that are not
+supported in Spring. These are: `call, get, set, preinitialization,
+staticinitialization, initialization, handler, adviceexecution, withincode, cflow,
+cflowbelow, if, @this`, and `@withincode`. Use of these pointcut designators in pointcut
+expressions interpreted by Spring AOP will result in an `IllegalArgumentException` being
+thrown.
+
+The set of pointcut designators supported by Spring AOP may be extended in future
+releases to support more of the AspectJ pointcut designators.
+****
+
+* __execution__ - for matching method execution join points, this is the primary
+ pointcut designator you will use when working with Spring AOP
+* __within__ - limits matching to join points within certain types (simply the execution
+ of a method declared within a matching type when using Spring AOP)
+* __this__ - limits matching to join points (the execution of methods when using Spring
+ AOP) where the bean reference (Spring AOP proxy) is an instance of the given type
+* __target__ - limits matching to join points (the execution of methods when using
+ Spring AOP) where the target object (application object being proxied) is an instance
+ of the given type
+* __args__ - limits matching to join points (the execution of methods when using Spring
+ AOP) where the arguments are instances of the given types
+* __@target__ - limits matching to join points (the execution of methods when using
+ Spring AOP) where the class of the executing object has an annotation of the given type
+* __@args__ - limits matching to join points (the execution of methods when using Spring
+ AOP) where the runtime type of the actual arguments passed have annotations of the
+ given type(s)
+* __@within__ - limits matching to join points within types that have the given
+ annotation (the execution of methods declared in types with the given annotation when
+ using Spring AOP)
+* __@annotation__ - limits matching to join points where the subject of the join point
+ (method being executed in Spring AOP) has the given annotation
+
+Because Spring AOP limits matching to only method execution join points, the discussion
+of the pointcut designators above gives a narrower definition than you will find in the
+AspectJ programming guide. In addition, AspectJ itself has type-based semantics and at
+an execution join point both '++this++' and '++target++' refer to the same object - the
+object executing the method. Spring AOP is a proxy-based system and differentiates
+between the proxy object itself (bound to '++this++') and the target object behind the
+proxy (bound to '++target++').
+
+[NOTE]
+====
+Due to the proxy-based nature of Spring's AOP framework, protected methods are by
+definition __not__ intercepted, neither for JDK proxies (where this isn't applicable)
+nor for CGLIB proxies (where this is technically possible but not recommendable for AOP
+purposes). As a consequence, any given pointcut will be matched against __public methods
+only__!
+
+If your interception needs include protected/private methods or even constructors,
+consider the use of Spring-driven <> instead of
+Spring's proxy-based AOP framework. This constitutes a different mode of AOP usage with
+different characteristics, so be sure to make yourself familiar with weaving first
+before making a decision.
+====
+
+Spring AOP also supports an additional PCD named '++bean++'. This PCD allows you to limit
+the matching of join points to a particular named Spring bean, or to a set of named
+Spring beans (when using wildcards). The '++bean++' PCD has the following form:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ bean(idOrNameOfBean)
+----
+
+The '++idOrNameOfBean++' token can be the name of any Spring bean: limited wildcard
+support using the '++*++' character is provided, so if you establish some naming
+conventions for your Spring beans you can quite easily write a '++bean++' PCD expression
+to pick them out. As is the case with other pointcut designators, the '++bean++' PCD can
+be &&'ed, ||'ed, and ! (negated) too.
+
+[NOTE]
+====
+Please note that the '++bean++' PCD is __only__ supported in Spring AOP - and __not__ in
+native AspectJ weaving. It is a Spring-specific extension to the standard PCDs that
+AspectJ defines.
+
+The '++bean++' PCD operates at the __instance__ level (building on the Spring bean name
+concept) rather than at the type level only (which is what weaving-based AOP is limited
+to). Instance-based pointcut designators are a special capability of Spring's
+proxy-based AOP framework and its close integration with the Spring bean factory, where
+it is natural and straightforward to identify specific beans by name.
+====
+
+
+[[aop-pointcuts-combining]]
+===== Combining pointcut expressions
+Pointcut expressions can be combined using '&&', '||' and '!'. It is also possible to
+refer to pointcut expressions by name. The following example shows three pointcut
+expressions: `anyPublicOperation` (which matches if a method execution join point
+represents the execution of any public method); `inTrading` (which matches if a method
+execution is in the trading module), and `tradingOperation` (which matches if a method
+execution represents any public method in the trading module).
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Pointcut("execution(public * *(..))")
+ private void anyPublicOperation() {}
+
+ @Pointcut("within(com.xyz.someapp.trading..*)")
+ private void inTrading() {}
+
+ @Pointcut("anyPublicOperation() && inTrading()")
+ private void tradingOperation() {}
+----
+
+It is a best practice to build more complex pointcut expressions out of smaller named
+components as shown above. When referring to pointcuts by name, normal Java visibility
+rules apply (you can see private pointcuts in the same type, protected pointcuts in the
+hierarchy, public pointcuts anywhere and so on). Visibility does not affect pointcut
+__matching__.
+
+
+[[aop-common-pointcuts]]
+===== Sharing common pointcut definitions
+When working with enterprise applications, you often want to refer to modules of the
+application and particular sets of operations from within several aspects. We recommend
+defining a "SystemArchitecture" aspect that captures common pointcut expressions for
+this purpose. A typical such aspect would look as follows:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ package com.xyz.someapp;
+
+ import org.aspectj.lang.annotation.Aspect;
+ import org.aspectj.lang.annotation.Pointcut;
+
+ @Aspect
+ public class SystemArchitecture {
+
+ /**
+ * A join point is in the web layer if the method is defined
+ * in a type in the com.xyz.someapp.web package or any sub-package
+ * under that.
+ */
+ @Pointcut("within(com.xyz.someapp.web..*)")
+ public void inWebLayer() {}
+
+ /**
+ * A join point is in the service layer if the method is defined
+ * in a type in the com.xyz.someapp.service package or any sub-package
+ * under that.
+ */
+ @Pointcut("within(com.xyz.someapp.service..*)")
+ public void inServiceLayer() {}
+
+ /**
+ * A join point is in the data access layer if the method is defined
+ * in a type in the com.xyz.someapp.dao package or any sub-package
+ * under that.
+ */
+ @Pointcut("within(com.xyz.someapp.dao..*)")
+ public void inDataAccessLayer() {}
+
+ /**
+ * A business service is the execution of any method defined on a service
+ * interface. This definition assumes that interfaces are placed in the
+ * "service" package, and that implementation types are in sub-packages.
+ *
+ * If you group service interfaces by functional area (for example,
+ * in packages com.xyz.someapp.abc.service and com.xyz.someapp.def.service) then
+ * the pointcut expression "execution(* com.xyz.someapp..service.*.*(..))"
+ * could be used instead.
+ *
+ * Alternatively, you can write the expression using the 'bean'
+ * PCD, like so "bean(*Service)". (This assumes that you have
+ * named your Spring service beans in a consistent fashion.)
+ */
+ @Pointcut("execution(* com.xyz.someapp..service.*.*(..))")
+ public void businessService() {}
+
+ /**
+ * A data access operation is the execution of any method defined on a
+ * dao interface. This definition assumes that interfaces are placed in the
+ * "dao" package, and that implementation types are in sub-packages.
+ */
+ @Pointcut("execution(* com.xyz.someapp.dao.*.*(..))")
+ public void dataAccessOperation() {}
+
+ }
+----
+
+The pointcuts defined in such an aspect can be referred to anywhere that you need a
+pointcut expression. For example, to make the service layer transactional, you could
+write:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+
+----
+
+The `` and `` elements are discussed in <>. The
+transaction elements are discussed in <>.
+
+
+[[aop-pointcuts-examples]]
+===== Examples
+Spring AOP users are likely to use the `execution` pointcut designator the most often.
+The format of an execution expression is:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern)
+ throws-pattern?)
+----
+
+All parts except the returning type pattern (ret-type-pattern in the snippet above),
+name pattern, and parameters pattern are optional. The returning type pattern determines
+what the return type of the method must be in order for a join point to be matched. Most
+frequently you will use `*` as the returning type pattern, which matches any return
+type. A fully-qualified type name will match only when the method returns the given
+type. The name pattern matches the method name. You can use the `*` wildcard as all or
+part of a name pattern. The parameters pattern is slightly more complex: `()` matches a
+method that takes no parameters, whereas `(..)` matches any number of parameters (zero
+or more). The pattern `(*)` matches a method taking one parameter of any type,
+`(*,String)` matches a method taking two parameters, the first can be of any type, the
+second must be a String. Consult the
+http://www.eclipse.org/aspectj/doc/released/progguide/semantics-pointcuts.html[Language
+Semantics] section of the AspectJ Programming Guide for more information.
+
+Some examples of common pointcut expressions are given below.
+
+* the execution of any public method:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ execution(public * *(..))
+----
+
+* the execution of any method with a name beginning with "set":
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ execution(* set*(..))
+----
+
+* the execution of any method defined by the `AccountService` interface:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ execution(* com.xyz.service.AccountService.*(..))
+----
+
+* the execution of any method defined in the service package:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ execution(* com.xyz.service.*.*(..))
+----
+
+* the execution of any method defined in the service package or a sub-package:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ execution(* com.xyz.service..*.*(..))
+----
+
+* any join point (method execution only in Spring AOP) within the service package:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ within(com.xyz.service.*)
+----
+
+* any join point (method execution only in Spring AOP) within the service package or a
+ sub-package:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ within(com.xyz.service..*)
+----
+
+* any join point (method execution only in Spring AOP) where the proxy implements the
+ `AccountService` interface:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ this(com.xyz.service.AccountService)
+----
+
+[NOTE]
+====
+'this' is more commonly used in a binding form :- see the following section on advice
+for how to make the proxy object available in the advice body.
+====
+
+* any join point (method execution only in Spring AOP) where the target object
+ implements the `AccountService` interface:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ target(com.xyz.service.AccountService)
+----
+
+[NOTE]
+====
+'target' is more commonly used in a binding form :- see the following section on advice
+for how to make the target object available in the advice body.
+====
+
+* any join point (method execution only in Spring AOP) which takes a single parameter,
+ and where the argument passed at runtime is `Serializable`:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ args(java.io.Serializable)
+----
+
+[NOTE]
+====
+'args' is more commonly used in a binding form :- see the following section on advice
+for how to make the method arguments available in the advice body.
+====
+
+Note that the pointcut given in this example is different to `execution(*
+*(java.io.Serializable))`: the args version matches if the argument passed at runtime is
+Serializable, the execution version matches if the method signature declares a single
+parameter of type `Serializable`.
+
+* any join point (method execution only in Spring AOP) where the target object has an
+ `@Transactional` annotation:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @target(org.springframework.transaction.annotation.Transactional)
+----
+
+[NOTE]
+====
+'@target' can also be used in a binding form :- see the following section on advice for
+how to make the annotation object available in the advice body.
+====
+
+* any join point (method execution only in Spring AOP) where the declared type of the
+ target object has an `@Transactional` annotation:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @within(org.springframework.transaction.annotation.Transactional)
+----
+
+[NOTE]
+====
+'@within' can also be used in a binding form :- see the following section on advice for
+how to make the annotation object available in the advice body.
+====
+
+* any join point (method execution only in Spring AOP) where the executing method has an
+ `@Transactional` annotation:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @annotation(org.springframework.transaction.annotation.Transactional)
+----
+
+[NOTE]
+====
+'@annotation' can also be used in a binding form :- see the following section on advice
+for how to make the annotation object available in the advice body.
+====
+
+* any join point (method execution only in Spring AOP) which takes a single parameter,
+ and where the runtime type of the argument passed has the `@Classified` annotation:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @args(com.xyz.security.Classified)
+----
+
+[NOTE]
+====
+'@args' can also be used in a binding form :- see the following section on advice for
+how to make the annotation object(s) available in the advice body.
+====
+
+* any join point (method execution only in Spring AOP) on a Spring bean named
+ '++tradeService++':
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ bean(tradeService)
+----
+
+* any join point (method execution only in Spring AOP) on Spring beans having names that
+ match the wildcard expression '++*Service++':
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ bean(*Service)
+----
+
+
+[[writing-good-pointcuts]]
+===== Writing good pointcuts
+During compilation, AspectJ processes pointcuts in order to try and optimize matching
+performance. Examining code and determining if each join point matches (statically or
+dynamically) a given pointcut is a costly process. (A dynamic match means the match
+cannot be fully determined from static analysis and a test will be placed in the code to
+determine if there is an actual match when the code is running). On first encountering a
+pointcut declaration, AspectJ will rewrite it into an optimal form for the matching
+process. What does this mean? Basically pointcuts are rewritten in DNF (Disjunctive
+Normal Form) and the components of the pointcut are sorted such that those components
+that are cheaper to evaluate are checked first. This means you do not have to worry
+about understanding the performance of various pointcut designators and may supply them
+in any order in a pointcut declaration.
+
+However, AspectJ can only work with what it is told, and for optimal performance of
+matching you should think about what they are trying to achieve and narrow the search
+space for matches as much as possible in the definition. The existing designators
+naturally fall into one of three groups: kinded, scoping and context:
+
+* Kinded designators are those which select a particular kind of join point. For
+ example: execution, get, set, call, handler
+* Scoping designators are those which select a group of join points of interest (of
+ probably many kinds). For example: within, withincode
+* Contextual designators are those that match (and optionally bind) based on context.
+ For example: this, target, @annotation
+
+A well written pointcut should try and include at least the first two types (kinded and
+scoping), whilst the contextual designators may be included if wishing to match based on
+join point context, or bind that context for use in the advice. Supplying either just a
+kinded designator or just a contextual designator will work but could affect weaving
+performance (time and memory used) due to all the extra processing and analysis. Scoping
+designators are very fast to match and their usage means AspectJ can very quickly
+dismiss groups of join points that should not be further processed - that is why a good
+pointcut should always include one if possible.
+
+
+
+[[aop-advice]]
+==== Declaring advice
+Advice is associated with a pointcut expression, and runs before, after, or around
+method executions matched by the pointcut. The pointcut expression may be either a
+simple reference to a named pointcut, or a pointcut expression declared in place.
+
+
+[[aop-advice-before]]
+===== Before advice
+Before advice is declared in an aspect using the `@Before` annotation:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ import org.aspectj.lang.annotation.Aspect;
+ import org.aspectj.lang.annotation.Before;
+
+ @Aspect
+ public class BeforeExample {
+
+ @Before("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
+ public void doAccessCheck() {
+ // ...
+ }
+
+ }
+----
+
+If using an in-place pointcut expression we could rewrite the above example as:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ import org.aspectj.lang.annotation.Aspect;
+ import org.aspectj.lang.annotation.Before;
+
+ @Aspect
+ public class BeforeExample {
+
+ @Before("execution(* com.xyz.myapp.dao.*.*(..))")
+ public void doAccessCheck() {
+ // ...
+ }
+
+ }
+----
+
+
+[[aop-advice-after-returning]]
+===== After returning advice
+After returning advice runs when a matched method execution returns normally. It is
+declared using the `@AfterReturning` annotation:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ import org.aspectj.lang.annotation.Aspect;
+ import org.aspectj.lang.annotation.AfterReturning;
+
+ @Aspect
+ public class AfterReturningExample {
+
+ @AfterReturning("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
+ public void doAccessCheck() {
+ // ...
+ }
+
+ }
+----
+
+[NOTE]
+====
+Note: it is of course possible to have multiple advice declarations, and other members
+as well, all inside the same aspect. We're just showing a single advice declaration in
+these examples to focus on the issue under discussion at the time.
+====
+
+Sometimes you need access in the advice body to the actual value that was returned. You
+can use the form of `@AfterReturning` that binds the return value for this:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ import org.aspectj.lang.annotation.Aspect;
+ import org.aspectj.lang.annotation.AfterReturning;
+
+ @Aspect
+ public class AfterReturningExample {
+
+ @AfterReturning(
+ pointcut="com.xyz.myapp.SystemArchitecture.dataAccessOperation()",
+ returning="retVal")
+ public void doAccessCheck(Object retVal) {
+ // ...
+ }
+
+ }
+----
+
+The name used in the `returning` attribute must correspond to the name of a parameter in
+the advice method. When a method execution returns, the return value will be passed to
+the advice method as the corresponding argument value. A `returning` clause also
+restricts matching to only those method executions that return a value of the specified
+type ( `Object` in this case, which will match any return value).
+
+Please note that it is __not__ possible to return a totally different reference when
+using after-returning advice.
+
+
+[[aop-advice-after-throwing]]
+===== After throwing advice
+After throwing advice runs when a matched method execution exits by throwing an
+exception. It is declared using the `@AfterThrowing` annotation:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ import org.aspectj.lang.annotation.Aspect;
+ import org.aspectj.lang.annotation.AfterThrowing;
+
+ @Aspect
+ public class AfterThrowingExample {
+
+ @AfterThrowing("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
+ public void doRecoveryActions() {
+ // ...
+ }
+
+ }
+----
+
+Often you want the advice to run only when exceptions of a given type are thrown, and
+you also often need access to the thrown exception in the advice body. Use the
+`throwing` attribute to both restrict matching (if desired, use `Throwable` as the
+exception type otherwise) and bind the thrown exception to an advice parameter.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ import org.aspectj.lang.annotation.Aspect;
+ import org.aspectj.lang.annotation.AfterThrowing;
+
+ @Aspect
+ public class AfterThrowingExample {
+
+ @AfterThrowing(
+ pointcut="com.xyz.myapp.SystemArchitecture.dataAccessOperation()",
+ throwing="ex")
+ public void doRecoveryActions(DataAccessException ex) {
+ // ...
+ }
+
+ }
+----
+
+The name used in the `throwing` attribute must correspond to the name of a parameter in
+the advice method. When a method execution exits by throwing an exception, the exception
+will be passed to the advice method as the corresponding argument value. A `throwing`
+clause also restricts matching to only those method executions that throw an exception
+of the specified type ( `DataAccessException` in this case).
+
+
+[[aop-advice-after-finally]]
+===== After (finally) advice
+After (finally) advice runs however a matched method execution exits. It is declared
+using the `@After` annotation. After advice must be prepared to handle both normal and
+exception return conditions. It is typically used for releasing resources, etc.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ import org.aspectj.lang.annotation.Aspect;
+ import org.aspectj.lang.annotation.After;
+
+ @Aspect
+ public class AfterFinallyExample {
+
+ @After("com.xyz.myapp.SystemArchitecture.dataAccessOperation()")
+ public void doReleaseLock() {
+ // ...
+ }
+
+ }
+----
+
+
+[[aop-ataspectj-around-advice]]
+===== Around advice
+The final kind of advice is around advice. Around advice runs "around" a matched method
+execution. It has the opportunity to do work both before and after the method executes,
+and to determine when, how, and even if, the method actually gets to execute at all.
+Around advice is often used if you need to share state before and after a method
+execution in a thread-safe manner (starting and stopping a timer for example). Always
+use the least powerful form of advice that meets your requirements (i.e. don't use
+around advice if simple before advice would do).
+
+Around advice is declared using the `@Around` annotation. The first parameter of the
+advice method must be of type `ProceedingJoinPoint`. Within the body of the advice,
+calling `proceed()` on the `ProceedingJoinPoint` causes the underlying method to
+execute. The `proceed` method may also be called passing in an `Object[]` - the values
+in the array will be used as the arguments to the method execution when it proceeds.
+
+[NOTE]
+====
+The behavior of proceed when called with an Object[] is a little different than the
+behavior of proceed for around advice compiled by the AspectJ compiler. For around
+advice written using the traditional AspectJ language, the number of arguments passed to
+proceed must match the number of arguments passed to the around advice (not the number
+of arguments taken by the underlying join point), and the value passed to proceed in a
+given argument position supplants the original value at the join point for the entity
+the value was bound to (Don't worry if this doesn't make sense right now!). The approach
+taken by Spring is simpler and a better match to its proxy-based, execution only
+semantics. You only need to be aware of this difference if you are compiling @AspectJ
+aspects written for Spring and using proceed with arguments with the AspectJ compiler
+and weaver. There is a way to write such aspects that is 100% compatible across both
+Spring AOP and AspectJ, and this is discussed in the following section on advice
+parameters.
+====
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ import org.aspectj.lang.annotation.Aspect;
+ import org.aspectj.lang.annotation.Around;
+ import org.aspectj.lang.ProceedingJoinPoint;
+
+ @Aspect
+ public class AroundExample {
+
+ @Around("com.xyz.myapp.SystemArchitecture.businessService()")
+ public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
+ // start stopwatch
+ Object retVal = pjp.proceed();
+ // stop stopwatch
+ return retVal;
+ }
+
+ }
+----
+
+The value returned by the around advice will be the return value seen by the caller of
+the method. A simple caching aspect for example could return a value from a cache if it
+has one, and invoke proceed() if it does not. Note that proceed may be invoked once,
+many times, or not at all within the body of the around advice, all of these are quite
+legal.
+
+
+[[aop-ataspectj-advice-params]]
+===== Advice parameters
+Spring offers fully typed advice - meaning that you declare the parameters you need
+in the advice signature (as we saw for the returning and throwing examples above) rather
+than work with `Object[]` arrays all the time. We'll see how to make argument and other
+contextual values available to the advice body in a moment. First let's take a look at
+how to write generic advice that can find out about the method the advice is currently
+advising.
+
+[[aop-ataspectj-advice-params-the-joinpoint]]
+====== Access to the current JoinPoint
+
+Any advice method may declare as its first parameter, a parameter of type
+`org.aspectj.lang.JoinPoint` (please note that around advice is __required__ to declare
+a first parameter of type `ProceedingJoinPoint`, which is a subclass of `JoinPoint`. The
+`JoinPoint` interface provides a number of useful methods such as `getArgs()` (returns
+the method arguments), `getThis()` (returns the proxy object), `getTarget()` (returns
+the target object), `getSignature()` (returns a description of the method that is being
+advised) and `toString()` (prints a useful description of the method being advised).
+Please do consult the javadocs for full details.
+
+[[aop-ataspectj-advice-params-passing]]
+====== Passing parameters to advice
+We've already seen how to bind the returned value or exception value (using after
+returning and after throwing advice). To make argument values available to the advice
+body, you can use the binding form of `args`. If a parameter name is used in place of a
+type name in an args expression, then the value of the corresponding argument will be
+passed as the parameter value when the advice is invoked. An example should make this
+clearer. Suppose you want to advise the execution of dao operations that take an Account
+object as the first parameter, and you need access to the account in the advice body.
+You could write the following:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Before("com.xyz.myapp.SystemArchitecture.dataAccessOperation() && args(account,..)")
+ public void validateAccount(Account account) {
+ // ...
+ }
+----
+
+The `args(account,..)` part of the pointcut expression serves two purposes: firstly, it
+restricts matching to only those method executions where the method takes at least one
+parameter, and the argument passed to that parameter is an instance of `Account`;
+secondly, it makes the actual `Account` object available to the advice via the `account`
+parameter.
+
+Another way of writing this is to declare a pointcut that "provides" the `Account`
+object value when it matches a join point, and then just refer to the named pointcut
+from the advice. This would look as follows:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Pointcut("com.xyz.myapp.SystemArchitecture.dataAccessOperation() && args(account,..)")
+ private void accountDataAccessOperation(Account account) {}
+
+ @Before("accountDataAccessOperation(account)")
+ public void validateAccount(Account account) {
+ // ...
+ }
+----
+
+The interested reader is once more referred to the AspectJ programming guide for more
+details.
+
+The proxy object ( `this`), target object ( `target`), and annotations ( `@within,
+@target, @annotation, @args`) can all be bound in a similar fashion. The following
+example shows how you could match the execution of methods annotated with an
+`@Auditable` annotation, and extract the audit code.
+
+First the definition of the `@Auditable` annotation:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Retention(RetentionPolicy.RUNTIME)
+ @Target(ElementType.METHOD)
+ public @interface Auditable {
+ AuditCode value();
+ }
+----
+
+And then the advice that matches the execution of `@Auditable` methods:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Before("com.xyz.lib.Pointcuts.anyPublicMethod() && @annotation(auditable)")
+ public void audit(Auditable auditable) {
+ AuditCode code = auditable.value();
+ // ...
+ }
+----
+
+[[aop-ataspectj-advice-params-generics]]
+====== Advice parameters and generics
+Spring AOP can handle generics used in class declarations and method parameters. Suppose
+you have a generic type like this:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public interface Sample {
+ void sampleGenericMethod(T param);
+ void sampleGenericCollectionMethod(Collection>T> param);
+ }
+----
+
+You can restrict interception of method types to certain parameter types by simply
+typing the advice parameter to the parameter type you want to intercept the method for:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Before("execution(* ..Sample+.sampleGenericMethod(*)) && args(param)")
+ public void beforeSampleMethod(MyType param) {
+ // Advice implementation
+ }
+----
+
+That this works is pretty obvious as we already discussed above. However, it's worth
+pointing out that this won't work for generic collections. So you cannot define a
+pointcut like this:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Before("execution(* ..Sample+.sampleGenericCollectionMethod(*)) && args(param)")
+ public void beforeSampleMethod(Collection param) {
+ // Advice implementation
+ }
+----
+
+To make this work we would have to inspect every element of the collection, which is not
+reasonable as we also cannot decide how to treat `null` values in general. To achieve
+something similar to this you have to type the parameter to `Collection>` and manually
+check the type of the elements.
+
+[[aop-ataspectj-advice-params-names]]
+====== Determining argument names
+The parameter binding in advice invocations relies on matching names used in pointcut
+expressions to declared parameter names in (advice and pointcut) method signatures.
+Parameter names are __not__ available through Java reflection, so Spring AOP uses the
+following strategies to determine parameter names:
+
+* If the parameter names have been specified by the user explicitly, then the specified
+ parameter names are used: both the advice and the pointcut annotations have
+ an optional "argNames" attribute which can be used to specify the argument names of
+ the annotated method - these argument names __are__ available at runtime. For example:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Before(value="com.xyz.lib.Pointcuts.anyPublicMethod() && target(bean) && @annotation(auditable)",
+ argNames="bean,auditable")
+ public void audit(Object bean, Auditable auditable) {
+ AuditCode code = auditable.value();
+ // ... use code and bean
+ }
+----
+
+If the first parameter is of the `JoinPoint`, `ProceedingJoinPoint`, or
+`JoinPoint.StaticPart` type, you may leave out the name of the parameter from the value
+of the "argNames" attribute. For example, if you modify the preceding advice to receive
+the join point object, the "argNames" attribute need not include it:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Before(value="com.xyz.lib.Pointcuts.anyPublicMethod() && target(bean) && @annotation(auditable)",
+ argNames="bean,auditable")
+ public void audit(JoinPoint jp, Object bean, Auditable auditable) {
+ AuditCode code = auditable.value();
+ // ... use code, bean, and jp
+ }
+----
+
+The special treatment given to the first parameter of the `JoinPoint`,
+`ProceedingJoinPoint`, and `JoinPoint.StaticPart` types is particularly convenient for
+advice that do not collect any other join point context. In such situations, you may
+simply omit the "argNames" attribute. For example, the following advice need not declare
+the "argNames" attribute:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Before("com.xyz.lib.Pointcuts.anyPublicMethod()")
+ public void audit(JoinPoint jp) {
+ // ... use jp
+ }
+----
+
+* Using the `'argNames'` attribute is a little clumsy, so if the `'argNames'` attribute
+ has not been specified, then Spring AOP will look at the debug information for the
+ class and try to determine the parameter names from the local variable table. This
+ information will be present as long as the classes have been compiled with debug
+ information ( `'-g:vars'` at a minimum). The consequences of compiling with this flag
+ on are: (1) your code will be slightly easier to understand (reverse engineer), (2)
+ the class file sizes will be very slightly bigger (typically inconsequential), (3) the
+ optimization to remove unused local variables will not be applied by your compiler. In
+ other words, you should encounter no difficulties building with this flag on.
+
+[NOTE]
+====
+If an @AspectJ aspect has been compiled by the AspectJ compiler (ajc) even without the
+debug information then there is no need to add the argNames attribute as the compiler
+will retain the needed information.
+====
+
+* If the code has been compiled without the necessary debug information, then Spring AOP
+ will attempt to deduce the pairing of binding variables to parameters (for example, if
+ only one variable is bound in the pointcut expression, and the advice method only
+ takes one parameter, the pairing is obvious!). If the binding of variables is
+ ambiguous given the available information, then an `AmbiguousBindingException` will be
+ thrown.
+* If all of the above strategies fail then an `IllegalArgumentException` will be thrown.
+
+[[aop-ataspectj-advice-proceeding-with-the-call]]
+====== Proceeding with arguments
+We remarked earlier that we would describe how to write a proceed call __with
+arguments__ that works consistently across Spring AOP and AspectJ. The solution is
+simply to ensure that the advice signature binds each of the method parameters in order.
+For example:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Around("execution(List find*(..)) && " +
+ "com.xyz.myapp.SystemArchitecture.inDataAccessLayer() && " +
+ "args(accountHolderNamePattern)")
+ public Object preProcessQueryPattern(ProceedingJoinPoint pjp,
+ String accountHolderNamePattern) throws Throwable {
+ String newPattern = preProcess(accountHolderNamePattern);
+ return pjp.proceed(new Object[] {newPattern});
+ }
+----
+
+In many cases you will be doing this binding anyway (as in the example above).
+
+
+[[aop-ataspectj-advice-ordering]]
+===== Advice ordering
+What happens when multiple pieces of advice all want to run at the same join point?
+Spring AOP follows the same precedence rules as AspectJ to determine the order of advice
+execution. The highest precedence advice runs first "on the way in" (so given two pieces
+of before advice, the one with highest precedence runs first). "On the way out" from a
+join point, the highest precedence advice runs last (so given two pieces of after
+advice, the one with the highest precedence will run second).
+
+When two pieces of advice defined in __different__ aspects both need to run at the same
+join point, unless you specify otherwise the order of execution is undefined. You can
+control the order of execution by specifying precedence. This is done in the normal
+Spring way by either implementing the `org.springframework.core.Ordered` interface in
+the aspect class or annotating it with the `Order` annotation. Given two aspects, the
+aspect returning the lower value from `Ordered.getValue()` (or the annotation value) has
+the higher precedence.
+
+When two pieces of advice defined in __the same__ aspect both need to run at the same
+join point, the ordering is undefined (since there is no way to retrieve the declaration
+order via reflection for javac-compiled classes). Consider collapsing such advice
+methods into one advice method per join point in each aspect class, or refactor the
+pieces of advice into separate aspect classes - which can be ordered at the aspect level.
+
+
+
+[[aop-introductions]]
+==== Introductions
+Introductions (known as inter-type declarations in AspectJ) enable an aspect to declare
+that advised objects implement a given interface, and to provide an implementation of
+that interface on behalf of those objects.
+
+An introduction is made using the `@DeclareParents` annotation. This annotation is used
+to declare that matching types have a new parent (hence the name). For example, given an
+interface `UsageTracked`, and an implementation of that interface `DefaultUsageTracked`,
+the following aspect declares that all implementors of service interfaces also implement
+the `UsageTracked` interface. (In order to expose statistics via JMX for example.)
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Aspect
+ public class UsageTracking {
+
+ @DeclareParents(value="com.xzy.myapp.service.*+", defaultImpl=DefaultUsageTracked.class)
+ public static UsageTracked mixin;
+
+ @Before("com.xyz.myapp.SystemArchitecture.businessService() && this(usageTracked)")
+ public void recordUsage(UsageTracked usageTracked) {
+ usageTracked.incrementUseCount();
+ }
+
+ }
+----
+
+The interface to be implemented is determined by the type of the annotated field. The
+`value` attribute of the `@DeclareParents` annotation is an AspectJ type pattern :- any
+bean of a matching type will implement the UsageTracked interface. Note that in the
+before advice of the above example, service beans can be directly used as
+implementations of the `UsageTracked` interface. If accessing a bean programmatically
+you would write the following:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ UsageTracked usageTracked = (UsageTracked) context.getBean("myService");
+----
+
+
+
+[[aop-instantiation-models]]
+==== Aspect instantiation models
+[NOTE]
+====
+(This is an advanced topic, so if you are just starting out with AOP you can safely skip
+it until later.)
+====
+
+By default there will be a single instance of each aspect within the application
+context. AspectJ calls this the singleton instantiation model. It is possible to define
+aspects with alternate lifecycles :- Spring supports AspectJ's `perthis` and `pertarget`
+instantiation models ( `percflow, percflowbelow,` and `pertypewithin` are not currently
+supported).
+
+A "perthis" aspect is declared by specifying a `perthis` clause in the `@Aspect`
+annotation. Let's look at an example, and then we'll explain how it works.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Aspect("perthis(com.xyz.myapp.SystemArchitecture.businessService())")
+ public class MyAspect {
+
+ private int someState;
+
+ @Before(com.xyz.myapp.SystemArchitecture.businessService())
+ public void recordServiceUsage() {
+ // ...
+ }
+
+ }
+----
+
+The effect of the `'perthis'` clause is that one aspect instance will be created for
+each unique service object executing a business service (each unique object bound to
+'this' at join points matched by the pointcut expression). The aspect instance is
+created the first time that a method is invoked on the service object. The aspect goes
+out of scope when the service object goes out of scope. Before the aspect instance is
+created, none of the advice within it executes. As soon as the aspect instance has been
+created, the advice declared within it will execute at matched join points, but only
+when the service object is the one this aspect is associated with. See the AspectJ
+programming guide for more information on per-clauses.
+
+The `'pertarget'` instantiation model works in exactly the same way as perthis, but
+creates one aspect instance for each unique target object at matched join points.
+
+
+
+[[aop-ataspectj-example]]
+==== Example
+Now that you have seen how all the constituent parts work, let's put them together to do
+something useful!
+
+The execution of business services can sometimes fail due to concurrency issues (for
+example, deadlock loser). If the operation is retried, it is quite likely to succeed
+next time round. For business services where it is appropriate to retry in such
+conditions (idempotent operations that don't need to go back to the user for conflict
+resolution), we'd like to transparently retry the operation to avoid the client seeing a
+`PessimisticLockingFailureException`. This is a requirement that clearly cuts across
+multiple services in the service layer, and hence is ideal for implementing via an
+aspect.
+
+Because we want to retry the operation, we will need to use around advice so that we can
+call proceed multiple times. Here's how the basic aspect implementation looks:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Aspect
+ public class ConcurrentOperationExecutor implements Ordered {
+
+ private static final int DEFAULT_MAX_RETRIES = 2;
+
+ private int maxRetries = DEFAULT_MAX_RETRIES;
+ private int order = 1;
+
+ public void setMaxRetries(int maxRetries) {
+ this.maxRetries = maxRetries;
+ }
+
+ public int getOrder() {
+ return this.order;
+ }
+
+ public void setOrder(int order) {
+ this.order = order;
+ }
+
+ @Around("com.xyz.myapp.SystemArchitecture.businessService()")
+ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
+ int numAttempts = 0;
+ PessimisticLockingFailureException lockFailureException;
+ do {
+ numAttempts++;
+ try {
+ return pjp.proceed();
+ }
+ catch(PessimisticLockingFailureException ex) {
+ lockFailureException = ex;
+ }
+ } while(numAttempts <= this.maxRetries);
+ throw lockFailureException;
+ }
+
+ }
+----
+
+Note that the aspect implements the `Ordered` interface so we can set the precedence of
+the aspect higher than the transaction advice (we want a fresh transaction each time we
+retry). The `maxRetries` and `order` properties will both be configured by Spring. The
+main action happens in the `doConcurrentOperation` around advice. Notice that for the
+moment we're applying the retry logic to all `businessService()s`. We try to proceed,
+and if we fail with an `PessimisticLockingFailureException` we simply try again unless
+we have exhausted all of our retry attempts.
+
+The corresponding Spring configuration is:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+----
+
+To refine the aspect so that it only retries idempotent operations, we might define an
+`Idempotent` annotation:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Retention(RetentionPolicy.RUNTIME)
+ public @interface Idempotent {
+ // marker annotation
+ }
+----
+
+and use the annotation to annotate the implementation of service operations. The change
+to the aspect to only retry idempotent operations simply involves refining the pointcut
+expression so that only `@Idempotent` operations match:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Around("com.xyz.myapp.SystemArchitecture.businessService() && " +
+ "@annotation(com.xyz.myapp.service.Idempotent)")
+ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
+ ...
+ }
+----
+
+
+
+
+[[aop-schema]]
+=== Schema-based AOP support
+If you prefer an XML-based format, then Spring also offers support for defining aspects
+using the new "aop" namespace tags. The exact same pointcut expressions and advice kinds
+are supported as when using the @AspectJ style, hence in this section we will focus on
+the new __syntax__ and refer the reader to the discussion in the previous section
+(<>) for an understanding of writing pointcut expressions and the binding
+of advice parameters.
+
+To use the aop namespace tags described in this section, you need to import the
+spring-aop schema as described in <>. See <>
+for how to import the tags in the aop namespace.
+
+Within your Spring configurations, all aspect and advisor elements must be placed within
+an `` element (you can have more than one `` element in an
+application context configuration). An `` element can contain pointcut,
+advisor, and aspect elements (note these must be declared in that order).
+
+[WARNING]
+====
+
+The `` style of configuration makes heavy use of Spring's
+<> mechanism. This can cause issues (such as advice not
+being woven) if you are already using explicit auto-proxying via the use of
+`BeanNameAutoProxyCreator` or suchlike. The recommended usage pattern is to use either
+just the `` style, or just the `AutoProxyCreator` style.
+====
+
+
+
+[[aop-schema-declaring-an-aspect]]
+==== Declaring an aspect
+Using the schema support, an aspect is simply a regular Java object defined as a bean in
+your Spring application context. The state and behavior is captured in the fields and
+methods of the object, and the pointcut and advice information is captured in the XML.
+
+An aspect is declared using the element, and the backing bean is referenced
+using the `ref` attribute:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+ ...
+
+
+
+
+ ...
+
+----
+
+The bean backing the aspect (" `aBean`" in this case) can of course be configured and
+dependency injected just like any other Spring bean.
+
+
+
+[[aop-schema-pointcuts]]
+==== Declaring a pointcut
+A named pointcut can be declared inside an element, enabling the pointcut
+definition to be shared across several aspects and advisors.
+
+A pointcut representing the execution of any business service in the service layer could
+be defined as follows:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+----
+
+Note that the pointcut expression itself is using the same AspectJ pointcut expression
+language as described in <>. If you are using the schema based
+declaration style, you can refer to named pointcuts defined in types
+(@Aspects) within the pointcut expression. Another way of defining the above pointcut
+would be:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+----
+
+Assuming you have a `SystemArchitecture` aspect as described in <>.
+
+Declaring a pointcut inside an aspect is very similar to declaring a top-level pointcut:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+ ...
+
+
+
+
+----
+
+Much the same way in an @AspectJ aspect, pointcuts declared using the schema based
+definition style may collect join point context. For example, the following pointcut
+collects the 'this' object as the join point context and passes it to advice:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+ ...
+
+
+
+
+----
+
+The advice must be declared to receive the collected join point context by including
+parameters of the matching names:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public void monitor(Object service) {
+ ...
+ }
+----
+
+When combining pointcut sub-expressions, '&&' is awkward within an XML document, and so
+the keywords 'and', 'or' and 'not' can be used in place of '&&', '||' and '!'
+respectively. For example, the previous pointcut may be better written as:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+ ...
+
+
+----
+
+Note that pointcuts defined in this way are referred to by their XML id and cannot be
+used as named pointcuts to form composite pointcuts. The named pointcut support in the
+schema based definition style is thus more limited than that offered by the @AspectJ
+style.
+
+
+
+[[aop-schema-advice]]
+==== Declaring advice
+The same five advice kinds are supported as for the @AspectJ style, and they have
+exactly the same semantics.
+
+
+[[aop-schema-advice-before]]
+===== Before advice
+Before advice runs before a matched method execution. It is declared inside an
+`` using the element.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+ ...
+
+
+----
+
+Here `dataAccessOperation` is the id of a pointcut defined at the top ( ``)
+level. To define the pointcut inline instead, replace the `pointcut-ref` attribute with
+a `pointcut` attribute:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+ ...
+
+
+----
+
+As we noted in the discussion of the @AspectJ style, using named pointcuts can
+significantly improve the readability of your code.
+
+The method attribute identifies a method ( `doAccessCheck`) that provides the body of
+the advice. This method must be defined for the bean referenced by the aspect element
+containing the advice. Before a data access operation is executed (a method execution
+join point matched by the pointcut expression), the "doAccessCheck" method on the aspect
+bean will be invoked.
+
+
+[[aop-schema-advice-after-returning]]
+===== After returning advice
+After returning advice runs when a matched method execution completes normally. It is
+declared inside an `` in the same way as before advice. For example:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+ ...
+
+
+----
+
+Just as in the @AspectJ style, it is possible to get hold of the return value within the
+advice body. Use the returning attribute to specify the name of the parameter to which
+the return value should be passed:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+ ...
+
+
+----
+
+The doAccessCheck method must declare a parameter named `retVal`. The type of this
+parameter constrains matching in the same way as described for @AfterReturning. For
+example, the method signature may be declared as:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public void doAccessCheck(Object retVal) {...
+----
+
+
+[[aop-schema-advice-after-throwing]]
+===== After throwing advice
+After throwing advice executes when a matched method execution exits by throwing an
+exception. It is declared inside an `` using the after-throwing element:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+ ...
+
+
+----
+
+Just as in the @AspectJ style, it is possible to get hold of the thrown exception within
+the advice body. Use the throwing attribute to specify the name of the parameter to
+which the exception should be passed:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+ ...
+
+
+----
+
+The doRecoveryActions method must declare a parameter named `dataAccessEx`. The type of
+this parameter constrains matching in the same way as described for @AfterThrowing. For
+example, the method signature may be declared as:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public void doRecoveryActions(DataAccessException dataAccessEx) {...
+----
+
+
+[[aop-schema-advice-after-finally]]
+===== After (finally) advice
+After (finally) advice runs however a matched method execution exits. It is declared
+using the `after` element:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+ ...
+
+
+----
+
+
+[[aop-schema-advice-around]]
+===== Around advice
+The final kind of advice is around advice. Around advice runs "around" a matched method
+execution. It has the opportunity to do work both before and after the method executes,
+and to determine when, how, and even if, the method actually gets to execute at all.
+Around advice is often used if you need to share state before and after a method
+execution in a thread-safe manner (starting and stopping a timer for example). Always
+use the least powerful form of advice that meets your requirements; don't use around
+advice if simple before advice would do.
+
+Around advice is declared using the `aop:around` element. The first parameter of the
+advice method must be of type `ProceedingJoinPoint`. Within the body of the advice,
+calling `proceed()` on the `ProceedingJoinPoint` causes the underlying method to
+execute. The `proceed` method may also be calling passing in an `Object[]` - the values
+in the array will be used as the arguments to the method execution when it proceeds. See
+<> for notes on calling proceed with an `Object[]`.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+ ...
+
+
+----
+
+The implementation of the `doBasicProfiling` advice would be exactly the same as in the
+@AspectJ example (minus the annotation of course):
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
+ // start stopwatch
+ Object retVal = pjp.proceed();
+ // stop stopwatch
+ return retVal;
+ }
+----
+
+
+[[aop-schema-params]]
+===== Advice parameters
+The schema based declaration style supports fully typed advice in the same way as
+described for the @AspectJ support - by matching pointcut parameters by name against
+advice method parameters. See <> for details. If you wish
+to explicitly specify argument names for the advice methods (not relying on the
+detection strategies previously described) then this is done using the `arg-names`
+attribute of the advice element, which is treated in the same manner to the "argNames"
+attribute in an advice annotation as described in <>.
+For example:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+----
+
+The `arg-names` attribute accepts a comma-delimited list of parameter names.
+
+Find below a slightly more involved example of the XSD-based approach that illustrates
+some around advice used in conjunction with a number of strongly typed parameters.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ package x.y.service;
+
+ public interface FooService {
+
+ Foo getFoo(String fooName, int age);
+ }
+
+ public class DefaultFooService implements FooService {
+
+ public Foo getFoo(String name, int age) {
+ return new Foo(name, age);
+ }
+ }
+----
+
+Next up is the aspect. Notice the fact that the `profile(..)` method accepts a number of
+strongly-typed parameters, the first of which happens to be the join point used to
+proceed with the method call: the presence of this parameter is an indication that the
+`profile(..)` is to be used as `around` advice:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ package x.y;
+
+ import org.aspectj.lang.ProceedingJoinPoint;
+ import org.springframework.util.StopWatch;
+
+ public class SimpleProfiler {
+
+ public Object profile(ProceedingJoinPoint call, String name, int age) throws Throwable {
+ StopWatch clock = new StopWatch("Profiling for '" + name + "' and '" + age + "'");
+ try {
+ clock.start(call.toShortString());
+ return call.proceed();
+ } finally {
+ clock.stop();
+ System.out.println(clock.prettyPrint());
+ }
+ }
+ }
+----
+
+Finally, here is the XML configuration that is required to effect the execution of the
+above advice for a particular join point:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+----
+
+If we had the following driver script, we would get output something like this on
+standard output:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ import org.springframework.beans.factory.BeanFactory;
+ import org.springframework.context.support.ClassPathXmlApplicationContext;
+ import x.y.service.FooService;
+
+ public final class Boot {
+
+ public static void main(final String[] args) throws Exception {
+ BeanFactory ctx = new ClassPathXmlApplicationContext("x/y/plain.xml");
+ FooService foo = (FooService) ctx.getBean("fooService");
+ foo.getFoo("Pengo", 12);
+ }
+ }
+----
+
+[literal]
+[subs="verbatim,quotes"]
+----
+StopWatch 'Profiling for 'Pengo' and '12'': running time (millis) = 0
+-----------------------------------------
+ms % Task name
+-----------------------------------------
+00000 ? execution(getFoo)
+----
+
+
+[[aop-ordering]]
+===== Advice ordering
+When multiple advice needs to execute at the same join point (executing method) the
+ordering rules are as described in <>. The precedence
+between aspects is determined by either adding the `Order` annotation to the bean
+backing the aspect or by having the bean implement the `Ordered` interface.
+
+
+
+[[aop-schema-introductions]]
+==== Introductions
+Introductions (known as inter-type declarations in AspectJ) enable an aspect to declare
+that advised objects implement a given interface, and to provide an implementation of
+that interface on behalf of those objects.
+
+An introduction is made using the `aop:declare-parents` element inside an `aop:aspect`
+This element is used to declare that matching types have a new parent (hence the name).
+For example, given an interface `UsageTracked`, and an implementation of that interface
+`DefaultUsageTracked`, the following aspect declares that all implementors of service
+interfaces also implement the `UsageTracked` interface. (In order to expose statistics
+via JMX for example.)
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+----
+
+The class backing the `usageTracking` bean would contain the method:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public void recordUsage(UsageTracked usageTracked) {
+ usageTracked.incrementUseCount();
+ }
+----
+
+The interface to be implemented is determined by `implement-interface` attribute. The
+value of the `types-matching` attribute is an AspectJ type pattern :- any bean of a
+matching type will implement the `UsageTracked` interface. Note that in the before
+advice of the above example, service beans can be directly used as implementations of
+the `UsageTracked` interface. If accessing a bean programmatically you would write the
+following:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ UsageTracked usageTracked = (UsageTracked) context.getBean("myService");
+----
+
+
+
+[[aop-schema-instatiation-models]]
+==== Aspect instantiation models
+The only supported instantiation model for schema-defined aspects is the singleton
+model. Other instantiation models may be supported in future releases.
+
+
+
+[[aop-schema-advisors]]
+==== Advisors
+The concept of "advisors" is brought forward from the AOP support defined in Spring 1.2
+and does not have a direct equivalent in AspectJ. An advisor is like a small
+self-contained aspect that has a single piece of advice. The advice itself is
+represented by a bean, and must implement one of the advice interfaces described in
+<>. Advisors can take advantage of AspectJ pointcut expressions
+though.
+
+Spring supports the advisor concept with the `` element. You will most
+commonly see it used in conjunction with transactional advice, which also has its own
+namespace support in Spring. Here's how it looks:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+
+
+
+
+
+----
+
+As well as the `pointcut-ref` attribute used in the above example, you can also use the
+`pointcut` attribute to define a pointcut expression inline.
+
+To define the precedence of an advisor so that the advice can participate in ordering,
+use the `order` attribute to define the `Ordered` value of the advisor.
+
+
+
+[[aop-schema-example]]
+==== Example
+Let's see how the concurrent locking failure retry example from
+<> looks when rewritten using the schema support.
+
+The execution of business services can sometimes fail due to concurrency issues (for
+example, deadlock loser). If the operation is retried, it is quite likely it will
+succeed next time round. For business services where it is appropriate to retry in such
+conditions (idempotent operations that don't need to go back to the user for conflict
+resolution), we'd like to transparently retry the operation to avoid the client seeing a
+`PessimisticLockingFailureException`. This is a requirement that clearly cuts across
+multiple services in the service layer, and hence is ideal for implementing via an
+aspect.
+
+Because we want to retry the operation, we'll need to use around advice so that we can
+call proceed multiple times. Here's how the basic aspect implementation looks (it's just
+a regular Java class using the schema support):
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class ConcurrentOperationExecutor implements Ordered {
+
+ private static final int DEFAULT_MAX_RETRIES = 2;
+
+ private int maxRetries = DEFAULT_MAX_RETRIES;
+ private int order = 1;
+
+ public void setMaxRetries(int maxRetries) {
+ this.maxRetries = maxRetries;
+ }
+
+ public int getOrder() {
+ return this.order;
+ }
+
+ public void setOrder(int order) {
+ this.order = order;
+ }
+
+ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
+ int numAttempts = 0;
+ PessimisticLockingFailureException lockFailureException;
+ do {
+ numAttempts++;
+ try {
+ return pjp.proceed();
+ }
+ catch(PessimisticLockingFailureException ex) {
+ lockFailureException = ex;
+ }
+ } while(numAttempts <= this.maxRetries);
+ throw lockFailureException;
+ }
+
+ }
+----
+
+Note that the aspect implements the `Ordered` interface so we can set the precedence of
+the aspect higher than the transaction advice (we want a fresh transaction each time we
+retry). The `maxRetries` and `order` properties will both be configured by Spring. The
+main action happens in the `doConcurrentOperation` around advice method. We try to
+proceed, and if we fail with a `PessimisticLockingFailureException` we simply try again
+unless we have exhausted all of our retry attempts.
+
+[NOTE]
+====
+This class is identical to the one used in the @AspectJ example, but with the
+annotations removed.
+====
+
+The corresponding Spring configuration is:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+----
+
+Notice that for the time being we assume that all business services are idempotent. If
+this is not the case we can refine the aspect so that it only retries genuinely
+idempotent operations, by introducing an `Idempotent` annotation:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Retention(RetentionPolicy.RUNTIME)
+ public @interface Idempotent {
+ // marker annotation
+ }
+----
+
+and using the annotation to annotate the implementation of service operations. The
+change to the aspect to retry only idempotent operations simply involves refining the
+pointcut expression so that only `@Idempotent` operations match:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+----
+
+
+
+
+[[aop-choosing]]
+=== Choosing which AOP declaration style to use
+Once you have decided that an aspect is the best approach for implementing a given
+requirement, how do you decide between using Spring AOP or AspectJ, and between the
+Aspect language (code) style, @AspectJ annotation style, or the Spring XML style? These
+decisions are influenced by a number of factors including application requirements,
+development tools, and team familiarity with AOP.
+
+
+
+[[aop-spring-or-aspectj]]
+==== Spring AOP or full AspectJ?
+Use the simplest thing that can work. Spring AOP is simpler than using full AspectJ as
+there is no requirement to introduce the AspectJ compiler / weaver into your development
+and build processes. If you only need to advise the execution of operations on Spring
+beans, then Spring AOP is the right choice. If you need to advise objects not managed by
+the Spring container (such as domain objects typically), then you will need to use
+AspectJ. You will also need to use AspectJ if you wish to advise join points other than
+simple method executions (for example, field get or set join points, and so on).
+
+When using AspectJ, you have the choice of the AspectJ language syntax (also known as
+the "code style") or the @AspectJ annotation style. Clearly, if you are not using Java
+5+ then the choice has been made for you... use the code style. If aspects play a large
+role in your design, and you are able to use the http://www.eclipse.org/ajdt/[AspectJ
+Development Tools (AJDT)] plugin for Eclipse, then the AspectJ language syntax is the
+preferred option: it is cleaner and simpler because the language was purposefully
+designed for writing aspects. If you are not using Eclipse, or have only a few aspects
+that do not play a major role in your application, then you may want to consider using
+the @AspectJ style and sticking with a regular Java compilation in your IDE, and adding
+an aspect weaving phase to your build script.
+
+
+
+[[aop-ataspectj-or-xml]]
+==== @AspectJ or XML for Spring AOP?
+If you have chosen to use Spring AOP, then you have a choice of @AspectJ or XML style.
+There are various tradeoffs to consider.
+
+The XML style will be most familiar to existing Spring users and it is backed by genuine
+POJOs. When using AOP as a tool to configure enterprise services then XML can be a good
+choice (a good test is whether you consider the pointcut expression to be a part of your
+configuration you might want to change independently). With the XML style arguably it is
+clearer from your configuration what aspects are present in the system.
+
+The XML style has two disadvantages. Firstly it does not fully encapsulate the
+implementation of the requirement it addresses in a single place. The DRY principle says
+that there should be a single, unambiguous, authoritative representation of any piece of
+knowledge within a system. When using the XML style, the knowledge of __how__ a
+requirement is implemented is split across the declaration of the backing bean class,
+and the XML in the configuration file. When using the @AspectJ style there is a single
+module - the aspect - in which this information is encapsulated. Secondly, the XML style
+is slightly more limited in what it can express than the @AspectJ style: only the
+"singleton" aspect instantiation model is supported, and it is not possible to combine
+named pointcuts declared in XML. For example, in the @AspectJ style you can write
+something like:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Pointcut(execution(* get*()))
+ public void propertyAccess() {}
+
+ @Pointcut(execution(org.xyz.Account+ *(..))
+ public void operationReturningAnAccount() {}
+
+ @Pointcut(propertyAccess() && operationReturningAnAccount())
+ public void accountPropertyAccess() {}
+----
+
+In the XML style I can declare the first two pointcuts:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+----
+
+The downside of the XML approach is that you cannot define the
+'++accountPropertyAccess++' pointcut by combining these definitions.
+
+The @AspectJ style supports additional instantiation models, and richer pointcut
+composition. It has the advantage of keeping the aspect as a modular unit. It also has
+the advantage the @AspectJ aspects can be understood (and thus consumed) both by Spring
+AOP and by AspectJ - so if you later decide you need the capabilities of AspectJ to
+implement additional requirements then it is very easy to migrate to an AspectJ-based
+approach. On balance the Spring team prefer the @AspectJ style whenever you have aspects
+that do more than simple "configuration" of enterprise services.
+
+
+
+
+[[aop-mixing-styles]]
+=== Mixing aspect types
+It is perfectly possible to mix @AspectJ style aspects using the autoproxying support,
+schema-defined `` aspects, `` declared advisors and even
+proxies and interceptors defined using the Spring 1.2 style in the same configuration.
+All of these are implemented using the same underlying support mechanism and will
+co-exist without any difficulty.
+
+
+
+
+[[aop-proxying]]
+=== Proxying mechanisms
+Spring AOP uses either JDK dynamic proxies or CGLIB to create the proxy for a given
+target object. (JDK dynamic proxies are preferred whenever you have a choice).
+
+If the target object to be proxied implements at least one interface then a JDK dynamic
+proxy will be used. All of the interfaces implemented by the target type will be
+proxied. If the target object does not implement any interfaces then a CGLIB proxy will
+be created.
+
+If you want to force the use of CGLIB proxying (for example, to proxy every method
+defined for the target object, not just those implemented by its interfaces) you can do
+so. However, there are some issues to consider:
+
+* `final` methods cannot be advised, as they cannot be overridden.
+* As of Spring 3.2, it is no longer necessary to add CGLIB to your project classpath, as
+ CGLIB classes are repackaged under org.springframework and included directly in the
+ spring-core JAR. This means that CGLIB-based proxy support 'just works' in the same
+ way that JDK dynamic proxies always have.
+* The constructor of your proxied object will be called twice. This is a natural
+ consequence of the CGLIB proxy model whereby a subclass is generated for each proxied
+ object. For each proxied instance, two objects are created: the actual proxied object
+ and an instance of the subclass that implements the advice. This behavior is not
+ exhibited when using JDK proxies. Usually, calling the constructor of the proxied type
+ twice, is not an issue, as there are usually only assignments taking place and no real
+ logic is implemented in the constructor.
+
+To force the use of CGLIB proxies set the value of the `proxy-target-class` attribute of
+the `` element to true:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+----
+
+To force CGLIB proxying when using the @AspectJ autoproxy support, set the
+`'proxy-target-class'` attribute of the `` element to `true`:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+----
+
+[NOTE]
+====
+Multiple `` sections are collapsed into a single unified auto-proxy creator
+at runtime, which applies the __strongest__ proxy settings that any of the
+`` sections (typically from different XML bean definition files) specified.
+This also applies to the `` and ``
+elements.
+
+To be clear: using '++proxy-target-class="true"++' on ``,
+`` or `` elements will force the use of CGLIB
+proxies __for all three of them__.
+====
+
+
+
+[[aop-understanding-aop-proxies]]
+==== Understanding AOP proxies
+Spring AOP is __proxy-based__. It is vitally important that you grasp the semantics of
+what that last statement actually means before you write your own aspects or use any of
+the Spring AOP-based aspects supplied with the Spring Framework.
+
+Consider first the scenario where you have a plain-vanilla, un-proxied,
+nothing-special-about-it, straight object reference, as illustrated by the following
+code snippet.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class SimplePojo implements Pojo {
+
+ public void foo() {
+ // this next method invocation is a direct call on the 'this' reference
+ this.bar();
+ }
+
+ public void bar() {
+ // some logic...
+ }
+ }
+----
+
+If you invoke a method on an object reference, the method is invoked __directly__ on
+that object reference, as can be seen below.
+
+image::images/aop-proxy-plain-pojo-call.png[width=400]
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class Main {
+
+ public static void main(String[] args) {
+
+ Pojo pojo = new SimplePojo();
+
+ // this is a direct method call on the 'pojo' reference
+ pojo.foo();
+ }
+ }
+----
+
+Things change slightly when the reference that client code has is a proxy. Consider the
+following diagram and code snippet.
+
+image::images/aop-proxy-call.png[width=400]
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class Main {
+
+ public static void main(String[] args) {
+
+ ProxyFactory factory = new ProxyFactory(new SimplePojo());
+ factory.addInterface(Pojo.class);
+ factory.addAdvice(new RetryAdvice());
+
+ Pojo pojo = (Pojo) factory.getProxy();
+
+ // this is a method call on the proxy!
+ pojo.foo();
+ }
+ }
+----
+
+The key thing to understand here is that the client code inside the `main(..)` of the
+`Main` class __has a reference to the proxy__. This means that method calls on that
+object reference will be calls on the proxy, and as such the proxy will be able to
+delegate to all of the interceptors (advice) that are relevant to that particular method
+call. However, once the call has finally reached the target object, the `SimplePojo`
+reference in this case, any method calls that it may make on itself, such as
+`this.bar()` or `this.foo()`, are going to be invoked against the __this__ reference,
+and __not__ the proxy. This has important implications. It means that self-invocation is
+__not__ going to result in the advice associated with a method invocation getting a
+chance to execute.
+
+Okay, so what is to be done about this? The best approach (the term best is used loosely
+here) is to refactor your code such that the self-invocation does not happen. For sure,
+this does entail some work on your part, but it is the best, least-invasive approach.
+The next approach is absolutely horrendous, and I am almost reticent to point it out
+precisely because it is so horrendous. You can (choke!) totally tie the logic within
+your class to Spring AOP by doing this:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class SimplePojo implements Pojo {
+
+ public void foo() {
+ // this works, but... gah!
+ ((Pojo) AopContext.currentProxy()).bar();
+ }
+
+ public void bar() {
+ // some logic...
+ }
+ }
+----
+
+This totally couples your code to Spring AOP, __and__ it makes the class itself aware of
+the fact that it is being used in an AOP context, which flies in the face of AOP. It
+also requires some additional configuration when the proxy is being created:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class Main {
+
+ public static void main(String[] args) {
+
+ ProxyFactory factory = new ProxyFactory(new SimplePojo());
+ factory.adddInterface(Pojo.class);
+ factory.addAdvice(new RetryAdvice());
+ factory.setExposeProxy(true);
+
+ Pojo pojo = (Pojo) factory.getProxy();
+
+ // this is a method call on the proxy!
+ pojo.foo();
+ }
+ }
+----
+
+Finally, it must be noted that AspectJ does not have this self-invocation issue because
+it is not a proxy-based AOP framework.
+
+
+
+
+[[aop-aspectj-programmatic]]
+=== Programmatic creation of @AspectJ Proxies
+In addition to declaring aspects in your configuration using either `` or
+``, it is also possible programmatically to create proxies that
+advise target objects. For the full details of Spring's AOP API, see the next chapter.
+Here we want to focus on the ability to automatically create proxies using @AspectJ
+aspects.
+
+The class `org.springframework.aop.aspectj.annotation.AspectJProxyFactory` can be used
+to create a proxy for a target object that is advised by one or more @AspectJ aspects.
+Basic usage for this class is very simple, as illustrated below. See the javadocs for
+full information.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ // create a factory that can generate a proxy for the given target object
+ AspectJProxyFactory factory = new AspectJProxyFactory(targetObject);
+
+ // add an aspect, the class must be an @AspectJ aspect
+ // you can call this as many times as you need with different aspects
+ factory.addAspect(SecurityManager.class);
+
+ // you can also add existing aspect instances, the type of the object supplied must be an @AspectJ aspect
+ factory.addAspect(usageTracker);
+
+ // now get the proxy object...
+ MyInterfaceType proxy = factory.getProxy();
+----
+
+
+
+
+[[aop-using-aspectj]]
+=== Using AspectJ with Spring applications
+Everything we've covered so far in this chapter is pure Spring AOP. In this section,
+we're going to look at how you can use the AspectJ compiler/weaver instead of, or in
+addition to, Spring AOP if your needs go beyond the facilities offered by Spring AOP
+alone.
+
+Spring ships with a small AspectJ aspect library, which is available standalone in your
+distribution as `spring-aspects.jar`; you'll need to add this to your classpath in order
+to use the aspects in it. <> and <> discuss the
+content of this library and how you can use it. <> discusses how to
+dependency inject AspectJ aspects that are woven using the AspectJ compiler. Finally,
+<> provides an introduction to load-time weaving for Spring applications
+using AspectJ.
+
+
+
+[[aop-atconfigurable]]
+==== Using AspectJ to dependency inject domain objects with Spring
+The Spring container instantiates and configures beans defined in your application
+context. It is also possible to ask a bean factory to configure a __pre-existing__
+object given the name of a bean definition containing the configuration to be applied.
+The `spring-aspects.jar` contains an annotation-driven aspect that exploits this
+capability to allow dependency injection of __any object__. The support is intended to
+be used for objects created __outside of the control of any container__. Domain objects
+often fall into this category because they are often created programmatically using the
+`new` operator, or by an ORM tool as a result of a database query.
+
+The `@Configurable` annotation marks a class as eligible for Spring-driven
+configuration. In the simplest case it can be used just as a marker annotation:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ package com.xyz.myapp.domain;
+
+ import org.springframework.beans.factory.annotation.Configurable;
+
+ @Configurable
+ public class Account {
+ // ...
+ }
+----
+
+When used as a marker interface in this way, Spring will configure new instances of the
+annotated type ( `Account` in this case) using a bean definition (typically
+prototype-scoped) with the same name as the fully-qualified type name (
+`com.xyz.myapp.domain.Account`). Since the default name for a bean is the
+fully-qualified name of its type, a convenient way to declare the prototype definition
+is simply to omit the `id` attribute:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+----
+
+If you want to explicitly specify the name of the prototype bean definition to use, you
+can do so directly in the annotation:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ package com.xyz.myapp.domain;
+
+ import org.springframework.beans.factory.annotation.Configurable;
+
+ @Configurable("account")
+ public class Account {
+ // ...
+ }
+----
+
+Spring will now look for a bean definition named " `account`" and use that as the
+definition to configure new `Account` instances.
+
+You can also use autowiring to avoid having to specify a dedicated bean definition at
+all. To have Spring apply autowiring use the '++autowire++' property of the
+`@Configurable` annotation: specify either `@Configurable(autowire=Autowire.BY_TYPE)` or
+`@Configurable(autowire=Autowire.BY_NAME` for autowiring by type or by name
+respectively. As an alternative, as of Spring 2.5 it is preferable to specify explicit,
+annotation-driven dependency injection for your `@Configurable` beans by using
+`@Autowired` or `@Inject` at the field or method level (see <>
+for further details).
+
+Finally you can enable Spring dependency checking for the object references in the newly
+created and configured object by using the `dependencyCheck` attribute (for example:
+`@Configurable(autowire=Autowire.BY_NAME,dependencyCheck=true)`). If this attribute is
+set to true, then Spring will validate after configuration that all properties (__which
+are not primitives or collections__) have been set.
+
+Using the annotation on its own does nothing of course. It is the
+`AnnotationBeanConfigurerAspect` in `spring-aspects.jar` that acts on the presence of
+the annotation. In essence the aspect says "after returning from the initialization of a
+new object of a type annotated with `@Configurable`, configure the newly created object
+using Spring in accordance with the properties of the annotation". In this context,
+__initialization__ refers to newly instantiated objects (e.g., objects instantiated with
+the '++new++' operator) as well as to `Serializable` objects that are undergoing
+deserialization (e.g., via
+http://docs.oracle.com/javase/6/docs/api/java/io/Serializable.html[readResolve()]).
+
+[NOTE]
+====
+One of the key phrases in the above paragraph is '__in essence__'. For most cases, the
+exact semantics of '__after returning from the initialization of a new object__' will be
+fine... in this context, '__after initialization__' means that the dependencies will be
+injected __after__ the object has been constructed - this means that the dependencies
+will not be available for use in the constructor bodies of the class. If you want the
+dependencies to be injected __before__ the constructor bodies execute, and thus be
+available for use in the body of the constructors, then you need to define this on the
+`@Configurable` declaration like so:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Configurable(preConstruction=true)
+----
+
+You can find out more information about the language semantics of the various pointcut
+types in AspectJ
+http://www.eclipse.org/aspectj/doc/next/progguide/semantics-joinPoints.html[in this
+appendix] of the http://www.eclipse.org/aspectj/doc/next/progguide/index.html[AspectJ
+Programming Guide].
+====
+
+For this to work the annotated types must be woven with the AspectJ weaver - you can
+either use a build-time Ant or Maven task to do this (see for example the
+http://www.eclipse.org/aspectj/doc/released/devguide/antTasks.html[AspectJ Development
+Environment Guide]) or load-time weaving (see <>). The
+`AnnotationBeanConfigurerAspect` itself needs configuring by Spring (in order to obtain
+a reference to the bean factory that is to be used to configure new objects). If you are
+using Java based configuration simply add `@EnableSpringConfigured` to any
+`@Configuration` class.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Configuration
+ @EnableSpringConfigured
+ public class AppConfig {
+
+ }
+----
+
+If you prefer XML based configuration, the Spring <> defines a convenient `context:spring-configured` element:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+----
+
+Instances of `@Configurable` objects created __before__ the aspect has been configured
+will result in a message being issued to the debug log and no configuration of the
+object taking place. An example might be a bean in the Spring configuration that creates
+domain objects when it is initialized by Spring. In this case you can use the
+"depends-on" bean attribute to manually specify that the bean depends on the
+configuration aspect.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+----
+
+[NOTE]
+====
+Do not activate `@Configurable` processing through the bean configurer aspect unless you
+really mean to rely on its semantics at runtime. In particular, make sure that you do
+not use `@Configurable` on bean classes which are registered as regular Spring beans
+with the container: You would get double initialization otherwise, once through the
+container and once through the aspect.
+====
+
+
+[[aop-configurable-testing]]
+===== Unit testing @Configurable objects
+
+One of the goals of the `@Configurable` support is to enable independent unit testing of
+domain objects without the difficulties associated with hard-coded lookups. If
+`@Configurable` types have not been woven by AspectJ then the annotation has no affect
+during unit testing, and you can simply set mock or stub property references in the
+object under test and proceed as normal. If `@Configurable` types __have__ been woven by
+AspectJ then you can still unit test outside of the container as normal, but you will
+see a warning message each time that you construct an `@Configurable` object indicating
+that it has not been configured by Spring.
+
+
+[[aop-configurable-container]]
+===== Working with multiple application contexts
+The `AnnotationBeanConfigurerAspect` used to implement the `@Configurable` support is an
+AspectJ singleton aspect. The scope of a singleton aspect is the same as the scope of
+`static` members, that is to say there is one aspect instance per classloader that
+defines the type. This means that if you define multiple application contexts within the
+same classloader hierarchy you need to consider where to define the
+`@EnableSpringConfigured` bean and where to place `spring-aspects.jar` on the classpath.
+
+Consider a typical Spring web-app configuration with a shared parent application context
+defining common business services and everything needed to support them, and one child
+application context per servlet containing definitions particular to that servlet. All
+of these contexts will co-exist within the same classloader hierarchy, and so the
+`AnnotationBeanConfigurerAspect` can only hold a reference to one of them. In this case
+we recommend defining the `@EnableSpringConfigured` bean in the shared (parent)
+application context: this defines the services that you are likely to want to inject
+into domain objects. A consequence is that you cannot configure domain objects with
+references to beans defined in the child (servlet-specific) contexts using the
+@Configurable mechanism (probably not something you want to do anyway!).
+
+When deploying multiple web-apps within the same container, ensure that each
+web-application loads the types in `spring-aspects.jar` using its own classloader (for
+example, by placing `spring-aspects.jar` in `'WEB-INF/lib'`). If `spring-aspects.jar` is
+only added to the container wide classpath (and hence loaded by the shared parent
+classloader), all web applications will share the same aspect instance which is probably
+not what you want.
+
+
+
+[[aop-ajlib-other]]
+==== Other Spring aspects for AspectJ
+In addition to the `@Configurable` aspect, `spring-aspects.jar` contains an AspectJ
+aspect that can be used to drive Spring's transaction management for types and methods
+annotated with the `@Transactional` annotation. This is primarily intended for users who
+want to use the Spring Framework's transaction support outside of the Spring container.
+
+The aspect that interprets `@Transactional` annotations is the
+`AnnotationTransactionAspect`. When using this aspect, you must annotate the
+__implementation__ class (and/or methods within that class), __not__ the interface (if
+any) that the class implements. AspectJ follows Java's rule that annotations on
+interfaces are __not inherited__.
+
+A `@Transactional` annotation on a class specifies the default transaction semantics for
+the execution of any __public__ operation in the class.
+
+A `@Transactional` annotation on a method within the class overrides the default
+transaction semantics given by the class annotation (if present). Methods with `public`,
+`protected`, and default visibility may all be annotated. Annotating `protected` and
+default visibility methods directly is the only way to get transaction demarcation for
+the execution of such methods.
+
+For AspectJ programmers that want to use the Spring configuration and transaction
+management support but don't want to (or cannot) use annotations, `spring-aspects.jar`
+also contains `abstract` aspects you can extend to provide your own pointcut
+definitions. See the sources for the `AbstractBeanConfigurerAspect` and
+`AbstractTransactionAspect` aspects for more information. As an example, the following
+excerpt shows how you could write an aspect to configure all instances of objects
+defined in the domain model using prototype bean definitions that match the
+fully-qualified class names:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public aspect DomainObjectConfiguration extends AbstractBeanConfigurerAspect {
+
+ public DomainObjectConfiguration() {
+ setBeanWiringInfoResolver(new ClassNameBeanWiringInfoResolver());
+ }
+
+ // the creation of a new bean (any object in the domain model)
+ protected pointcut beanCreation(Object beanInstance) :
+ initialization(new(..)) &&
+ SystemArchitecture.inDomainModel() &&
+ this(beanInstance);
+
+ }
+----
+
+
+
+[[aop-aj-configure]]
+==== Configuring AspectJ aspects using Spring IoC
+When using AspectJ aspects with Spring applications, it is natural to both want and
+expect to be able to configure such aspects using Spring. The AspectJ runtime itself is
+responsible for aspect creation, and the means of configuring the AspectJ created
+aspects via Spring depends on the AspectJ instantiation model (the '++per-xxx++' clause)
+used by the aspect.
+
+The majority of AspectJ aspects are __singleton__ aspects. Configuration of these
+aspects is very easy: simply create a bean definition referencing the aspect type as
+normal, and include the bean attribute `'factory-method="aspectOf"'`. This ensures that
+Spring obtains the aspect instance by asking AspectJ for it rather than trying to create
+an instance itself. For example:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+----
+
+Non-singleton aspects are harder to configure: however it is possible to do so by
+creating prototype bean definitions and using the `@Configurable` support from
+`spring-aspects.jar` to configure the aspect instances once they have bean created by
+the AspectJ runtime.
+
+If you have some @AspectJ aspects that you want to weave with AspectJ (for example,
+using load-time weaving for domain model types) and other @AspectJ aspects that you want
+to use with Spring AOP, and these aspects are all configured using Spring, then you will
+need to tell the Spring AOP @AspectJ autoproxying support which exact subset of the
+@AspectJ aspects defined in the configuration should be used for autoproxying. You can
+do this by using one or more `` elements inside the ``
+declaration. Each `` element specifies a name pattern, and only beans with
+names matched by at least one of the patterns will be used for Spring AOP autoproxy
+configuration:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+----
+
+[NOTE]
+====
+Do not be misled by the name of the `` element: using it will
+result in the creation of __Spring AOP proxies__. The @AspectJ style of aspect
+declaration is just being used here, but the AspectJ runtime is __not__ involved.
+====
+
+
+
+[[aop-aj-ltw]]
+==== Load-time weaving with AspectJ in the Spring Framework
+Load-time weaving (LTW) refers to the process of weaving AspectJ aspects into an
+application's class files as they are being loaded into the Java virtual machine (JVM).
+The focus of this section is on configuring and using LTW in the specific context of the
+Spring Framework: this section is not an introduction to LTW though. For full details on
+the specifics of LTW and configuring LTW with just AspectJ (with Spring not being
+involved at all), see the
+http://www.eclipse.org/aspectj/doc/released/devguide/ltw.html[LTW section of the AspectJ
+Development Environment Guide].
+
+The value-add that the Spring Framework brings to AspectJ LTW is in enabling much
+finer-grained control over the weaving process. 'Vanilla' AspectJ LTW is effected using
+a Java (5+) agent, which is switched on by specifying a VM argument when starting up a
+JVM. It is thus a JVM-wide setting, which may be fine in some situations, but often is a
+little too coarse. Spring-enabled LTW enables you to switch on LTW on a
+__per-ClassLoader__ basis, which obviously is more fine-grained and which can make more
+sense in a 'single-JVM-multiple-application' environment (such as is found in a typical
+application server environment).
+
+Further, <>, this support enables
+load-time weaving __without making any modifications to the application server's launch
+script__ that will be needed to add `-javaagent:path/to/aspectjweaver.jar` or (as we
+describe later in this section)
+`-javaagent:path/to/org.springframework.instrument-{version}.jar` (previously named
+`spring-agent.jar`). Developers simply modify one or more files that form the
+application context to enable load-time weaving instead of relying on administrators who
+typically are in charge of the deployment configuration such as the launch script.
+
+Now that the sales pitch is over, let us first walk through a quick example of AspectJ
+LTW using Spring, followed by detailed specifics about elements introduced in the
+following example. For a complete example, please see the
+https://github.com/spring-projects/spring-petclinic[Petclinic sample application].
+
+
+[[aop-aj-ltw-first-example]]
+===== A first example
+Let us assume that you are an application developer who has been tasked with diagnosing
+the cause of some performance problems in a system. Rather than break out a profiling
+tool, what we are going to do is switch on a simple profiling aspect that will enable us
+to very quickly get some performance metrics, so that we can then apply a finer-grained
+profiling tool to that specific area immediately afterwards.
+
+[NOTE]
+====
+The example presented here uses XML style configuration, it is also possible to
+configure and use @AspectJ with <>. Specifically the
+`@EnableLoadTimeWeaving` annotation can be used as an alternative to
+`` (see <> for details).
+====
+
+Here is the profiling aspect. Nothing too fancy, just a quick-and-dirty time-based
+profiler, using the @AspectJ-style of aspect declaration.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ package foo;
+
+ import org.aspectj.lang.ProceedingJoinPoint;
+ import org.aspectj.lang.annotation.Aspect;
+ import org.aspectj.lang.annotation.Around;
+ import org.aspectj.lang.annotation.Pointcut;
+ import org.springframework.util.StopWatch;
+ import org.springframework.core.annotation.Order;
+
+ @Aspect
+ public class ProfilingAspect {
+
+ @Around("methodsToBeProfiled()")
+ public Object profile(ProceedingJoinPoint pjp) throws Throwable {
+ StopWatch sw = new StopWatch(getClass().getSimpleName());
+ try {
+ sw.start(pjp.getSignature().getName());
+ return pjp.proceed();
+ } finally {
+ sw.stop();
+ System.out.println(sw.prettyPrint());
+ }
+ }
+
+ @Pointcut("execution(public * foo..*.*(..))")
+ public void methodsToBeProfiled(){}
+ }
+----
+
+We will also need to create an '++META-INF/aop.xml++' file, to inform the AspectJ weaver
+that we want to weave our `ProfilingAspect` into our classes. This file convention,
+namely the presence of a file (or files) on the Java classpath called
+'++META-INF/aop.xml++' is standard AspectJ.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+----
+
+Now to the Spring-specific portion of the configuration. We need to configure a
+`LoadTimeWeaver` (all explained later, just take it on trust for now). This load-time
+weaver is the essential component responsible for weaving the aspect configuration in
+one or more '++META-INF/aop.xml++' files into the classes in your application. The good
+thing is that it does not require a lot of configuration, as can be seen below (there
+are some more options that you can specify, but these are detailed later).
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+ ****
+
+----
+
+Now that all the required artifacts are in place - the aspect, the '++META-INF/aop.xml++'
+file, and the Spring configuration -, let us create a simple driver class with a
+`main(..)` method to demonstrate the LTW in action.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ package foo;
+
+ import org.springframework.context.support.ClassPathXmlApplicationContext;
+
+ public final class Main {
+
+ public static void main(String[] args) {
+
+ ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml", Main.class);
+
+ EntitlementCalculationService entitlementCalculationService
+ = (EntitlementCalculationService) ctx.getBean("entitlementCalculationService");
+
+ // the profiling aspect is 'woven' around this method execution
+ entitlementCalculationService.calculateEntitlement();
+ }
+ }
+----
+
+There is one last thing to do. The introduction to this section did say that one could
+switch on LTW selectively on a per- `ClassLoader` basis with Spring, and this is true.
+However, just for this example, we are going to use a Java agent (supplied with Spring)
+to switch on the LTW. This is the command line we will use to run the above `Main` class:
+
+[literal]
+[subs="verbatim,quotes"]
+----
+java -javaagent:C:/projects/foo/lib/global/spring-instrument.jar foo.Main
+----
+
+The '++-javaagent++' is a flag for specifying and enabling
+http://docs.oracle.com/javase/6/docs/api/java/lang/instrument/package-summary.html[agents
+to instrument programs running on the JVM]. The Spring Framework ships with such an
+agent, the `InstrumentationSavingAgent`, which is packaged in the
+`spring-instrument.jar` that was supplied as the value of the `-javaagent` argument in
+the above example.
+
+The output from the execution of the `Main` program will look something like that below.
+(I have introduced a `Thread.sleep(..)` statement into the `calculateEntitlement()`
+implementation so that the profiler actually captures something other than 0
+milliseconds - the `01234` milliseconds is __not__ an overhead introduced by the AOP :) )
+
+[literal]
+[subs="verbatim,quotes"]
+----
+Calculating entitlement
+
+StopWatch 'ProfilingAspect': running time (millis) = 1234
+------ ----- ----------------------------
+ms % Task name
+------ ----- ----------------------------
+01234 100% calculateEntitlement
+----
+
+Since this LTW is effected using full-blown AspectJ, we are not just limited to advising
+Spring beans; the following slight variation on the `Main` program will yield the same
+result.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ package foo;
+
+ import org.springframework.context.support.ClassPathXmlApplicationContext;
+
+ public final class Main {
+
+ public static void main(String[] args) {
+
+ new ClassPathXmlApplicationContext("beans.xml", Main.class);
+
+ EntitlementCalculationService entitlementCalculationService =
+ new StubEntitlementCalculationService();
+
+ // the profiling aspect will be 'woven' around this method execution
+ entitlementCalculationService.calculateEntitlement();
+ }
+ }
+----
+
+Notice how in the above program we are simply bootstrapping the Spring container, and
+then creating a new instance of the `StubEntitlementCalculationService` totally outside
+the context of Spring... the profiling advice still gets woven in.
+
+The example admittedly is simplistic... however the basics of the LTW support in Spring
+have all been introduced in the above example, and the rest of this section will explain
+the 'why' behind each bit of configuration and usage in detail.
+
+[NOTE]
+====
+The `ProfilingAspect` used in this example may be basic, but it is quite useful. It is a
+nice example of a development-time aspect that developers can use during development (of
+course), and then quite easily exclude from builds of the application being deployed
+into UAT or production.
+====
+
+
+[[aop-aj-ltw-the-aspects]]
+===== Aspects
+The aspects that you use in LTW have to be AspectJ aspects. They can be written in
+either the AspectJ language itself or you can write your aspects in the @AspectJ-style.
+It means that your aspects are then both valid AspectJ __and__ Spring AOP aspects.
+Furthermore, the compiled aspect classes need to be available on the classpath.
+
+
+[[aop-aj-ltw-aop_dot_xml]]
+===== 'META-INF/aop.xml'
+
+The AspectJ LTW infrastructure is configured using one or more '++META-INF/aop.xml++'
+files, that are on the Java classpath (either directly, or more typically in jar files).
+
+The structure and contents of this file is detailed in the main AspectJ reference
+documentation, and the interested reader is
+http://www.eclipse.org/aspectj/doc/released/devguide/ltw-configuration.html[referred to
+that resource]. (I appreciate that this section is brief, but the '++aop.xml++' file is
+100% AspectJ - there is no Spring-specific information or semantics that apply to it,
+and so there is no extra value that I can contribute either as a result), so rather than
+rehash the quite satisfactory section that the AspectJ developers wrote, I am just
+directing you there.)
+
+
+[[aop-aj-ltw-libraries]]
+===== Required libraries (JARS)
+At a minimum you will need the following libraries to use the Spring Framework's support
+for AspectJ LTW:
+
+* `spring-aop.jar` (version 2.5 or later, plus all mandatory dependencies)
+* `aspectjweaver.jar` (version 1.6.8 or later)
+
+If you are using the <>, you will also need:
+
+* `spring-instrument.jar`
+
+
+[[aop-aj-ltw-spring]]
+===== Spring configuration
+The key component in Spring's LTW support is the `LoadTimeWeaver` interface (in the
+`org.springframework.instrument.classloading` package), and the numerous implementations
+of it that ship with the Spring distribution. A `LoadTimeWeaver` is responsible for
+adding one or more `java.lang.instrument.ClassFileTransformers` to a `ClassLoader` at
+runtime, which opens the door to all manner of interesting applications, one of which
+happens to be the LTW of aspects.
+
+[TIP]
+====
+
+If you are unfamiliar with the idea of runtime class file transformation, you are
+encouraged to read the javadoc API documentation for the `java.lang.instrument` package
+before continuing. This is not a huge chore because there is - rather annoyingly -
+precious little documentation there... the key interfaces and classes will at least be
+laid out in front of you for reference as you read through this section.
+====
+
+Configuring a `LoadTimeWeaver` for a particular `ApplicationContext` can be as easy as
+adding one line. (Please note that you almost certainly will need to be using an
+`ApplicationContext` as your Spring container - typically a `BeanFactory` will not be
+enough because the LTW support makes use of `BeanFactoryPostProcessors`.)
+
+To enable the Spring Framework's LTW support, you need to configure a `LoadTimeWeaver`,
+which typically is done using the `@EnableLoadTimeWeaving` annotation.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Configuration
+ @EnableLoadTimeWeaving
+ public class AppConfig {
+
+ }
+----
+
+Alternatively, if you prefer XML based configuration, use the
+`` element. Note that the element is defined in the
+'++context++' namespace.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+----
+
+The above configuration will define and register a number of LTW-specific infrastructure
+beans for you automatically, such as a `LoadTimeWeaver` and an `AspectJWeavingEnabler`.
+The default `LoadTimeWeaver` is the `DefaultContextLoadTimeWeaver` class, which attempts
+to decorate an automatically detected `LoadTimeWeaver`: the exact type of
+`LoadTimeWeaver` that will be 'automatically detected' is dependent upon your runtime
+environment (summarized in the following table).
+
+[[aop-aj-ltw-spring-env-impls]]
+.DefaultContextLoadTimeWeaver LoadTimeWeavers
+|===
+| Runtime Environment| `LoadTimeWeaver` implementation
+
+| Running in
+ http://www.bea.com/framework.jsp?CNT=index.htm&FP=/content/products/weblogic/server[BEA's
+ Weblogic 10]
+| `WebLogicLoadTimeWeaver`
+
+| Running in http://www-01.ibm.com/software/webservers/appserv/was/[IBM WebSphere
+ Application Server 7]
+| `WebSphereLoadTimeWeaver`
+
+| Running in http://glassfish.dev.java.net/[GlassFish]
+| `GlassFishLoadTimeWeaver`
+
+| Running in http://www.jboss.org/jbossas/[JBoss AS]
+| `JBossLoadTimeWeaver`
+
+| JVM started with Spring `InstrumentationSavingAgent` __(java
+ -javaagent:path/to/spring-instrument.jar)__
+| `InstrumentationLoadTimeWeaver`
+
+| Fallback, expecting the underlying ClassLoader to follow common conventions (e.g.
+ applicable to `TomcatInstrumentableClassLoader` and http://www.caucho.com/[Resin])
+| `ReflectiveLoadTimeWeaver`
+|===
+
+Note that these are just the `LoadTimeWeavers` that are autodetected when using the
+`DefaultContextLoadTimeWeaver`: it is of course possible to specify exactly which
+`LoadTimeWeaver` implementation that you wish to use.
+
+To specify a specific `LoadTimeWeaver` with Java configuration implement the
+`LoadTimeWeavingConfigurer` interface and override the `getLoadTimeWeaver()` method:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ @Configuration
+ @EnableLoadTimeWeaving
+ public class AppConfig implements LoadTimeWeavingConfigurer {
+
+ @Override
+ public LoadTimeWeaver getLoadTimeWeaver() {
+ return new ReflectiveLoadTimeWeaver();
+ }
+ }
+----
+
+If you are using XML based configuration you can specify the fully-qualified classname
+as the value of the '++weaver-class++' attribute on the ``
+element:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+----
+
+The `LoadTimeWeaver` that is defined and registered by the configuration can be later
+retrieved from the Spring container using the well-known name '++loadTimeWeaver++'.
+Remember that the `LoadTimeWeaver` exists just as a mechanism for Spring's LTW
+infrastructure to add one or more `ClassFileTransformers`. The actual
+`ClassFileTransformer` that does the LTW is the `ClassPreProcessorAgentAdapter` (from
+the `org.aspectj.weaver.loadtime` package) class. See the class-level javadocs of the
+`ClassPreProcessorAgentAdapter` class for further details, because the specifics of how
+the weaving is actually effected is beyond the scope of this section.
+
+There is one final attribute of the configuration left to discuss: the
+'++aspectjWeaving++' attribute (or '++aspectj-weaving++' if you are using XML). This is a
+simple attribute that controls whether LTW is enabled or not; it is as simple as that.
+It accepts one of three possible values, summarized below, with the default value being
+'++autodetect++' if the attribute is not present.
+
+[[aop-aj-ltw-ltw-tag-attrs]]
+.AspectJ weaving attribute values
+|===
+| Annotation Value| XML Value| Explanation
+
+| `ENABLED`
+| `on`
+| AspectJ weaving is on, and aspects will be woven at load-time as appropriate.
+
+| `DISABLED`
+| `off`
+| LTW is off... no aspect will be woven at load-time.
+
+| `AUTODETECT`
+| `autodetect`
+| If the Spring LTW infrastructure can find at least one '++META-INF/aop.xml++' file,
+ then AspectJ weaving is on, else it is off. This is the default value.
+|===
+
+
+[[aop-aj-ltw-environments]]
+===== Environment-specific configuration
+This last section contains any additional settings and configuration that you will need
+when using Spring's LTW support in environments such as application servers and web
+containers.
+
+[[aop-aj-ltw-environment-tomcat]]
+====== Tomcat
+http://tomcat.apache.org/[Apache Tomcat]'s default class loader does not support class
+transformation which is why Spring provides an enhanced implementation that addresses
+this need. Named `TomcatInstrumentableClassLoader`, the loader works on Tomcat 5.0 and
+above and can be registered individually for __each__ web application as follows:
+
+* Tomcat 6.0.x or higher
+* Copy `org.springframework.instrument.tomcat.jar` into __$CATALINA_HOME__/lib, where
+ __$CATALINA_HOME__ represents the root of the Tomcat installation)
+* Instruct Tomcat to use the custom class loader (instead of the default) by editing the
+ web application context file:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+----
+
+Apache Tomcat (6.0+) supports several context locations:
+
+* server configuration file - __$CATALINA_HOME/conf/server.xml__
+* default context configuration - __$CATALINA_HOME/conf/context.xml__ - that affects all
+ deployed web applications
+* per-web application configuration which can be deployed either on the server-side at
+ __$CATALINA_HOME/conf/[enginename]/[hostname]/[webapp]-context.xml__ or embedded
+ inside the web-app archive at __META-INF/context.xml__
+
+For efficiency, the embedded per-web-app configuration style is recommended because it
+will impact only applications that use the custom class loader and does not require any
+changes to the server configuration. See the Tomcat 6.0.x
+http://tomcat.apache.org/tomcat-6.0-doc/config/context.html[documentation] for more
+details about available context locations.
+
+Alternatively, consider the use of the Spring-provided generic VM agent, to be specified
+in Tomcat's launch script (see above). This will make instrumentation available to all
+deployed web applications, no matter what ClassLoader they happen to run on.
+
+[[aop-aj-ltw-environments-weblogic-oc4j-resin-glassfish-jboss]]
+====== WebLogic, WebSphere, Resin, GlassFish, JBoss
+Recent versions of WebLogic Server (version 10 and above), IBM WebSphere Application
+Server (version 7 and above), Resin (3.1 and above) and JBoss (6.x or above) provide a
+ClassLoader that is capable of local instrumentation. Spring's native LTW leverages such
+ClassLoaders to enable AspectJ weaving. You can enable LTW by simply activating
+load-time weaving as described earlier. Specifically, you do __not__ need to modify the
+launch script to add `-javaagent:path/to/spring-instrument.jar`.
+
+Note that GlassFish instrumentation-capable ClassLoader is available only in its EAR
+environment. For GlassFish web applications, follow the Tomcat setup instructions as
+outlined above.
+
+Note that on JBoss 6.x, the app server scanning needs to be disabled to prevent it from
+loading the classes before the application actually starts. A quick workaround is to add
+to your artifact a file named `WEB-INF/jboss-scanning.xml` with the following content:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+----
+
+[[aop-aj-ltw-environment-generic]]
+====== Generic Java applications
+When class instrumentation is required in environments that do not support or are not
+supported by the existing `LoadTimeWeaver` implementations, a JDK agent can be the only
+solution. For such cases, Spring provides `InstrumentationLoadTimeWeaver`, which
+requires a Spring-specific (but very general) VM agent,
+`org.springframework.instrument-{version}.jar` (previously named `spring-agent.jar`).
+
+To use it, you must start the virtual machine with the Spring agent, by supplying the
+following JVM options:
+
+[literal]
+[subs="verbatim,quotes"]
+----
+-javaagent:/path/to/org.springframework.instrument-{version}.jar
+----
+
+Note that this requires modification of the VM launch script which may prevent you from
+using this in application server environments (depending on your operation policies).
+Additionally, the JDK agent will instrument the __entire__ VM which can prove expensive.
+
+For performance reasons, it is recommended to use this configuration only if your target
+environment (such as http://www.eclipse.org/jetty/[Jetty]) does not have (or does not
+support) a dedicated LTW.
+
+
+
+
+[[aop-resources]]
+=== Further Resources
+More information on AspectJ can be found on the http://www.eclipse.org/aspectj[AspectJ
+website].
+
+The book __Eclipse AspectJ__ by Adrian Colyer et. al. (Addison-Wesley, 2005) provides a
+comprehensive introduction and reference for the AspectJ language.
+
+The book __AspectJ in Action__ by Ramnivas Laddad (Manning, 2003) comes highly
+recommended; the focus of the book is on AspectJ, but a lot of general AOP themes are
+explored (in some depth).
diff --git a/src/asciidoc/appendix.adoc b/src/asciidoc/appendix.adoc
deleted file mode 100644
index cf46a041655e..000000000000
--- a/src/asciidoc/appendix.adoc
+++ /dev/null
@@ -1,6628 +0,0 @@
-[[spring-appendices]]
-= Appendices
-
-
-
-
-
-[[migration-4.0]]
-== Migrating to Spring Framework 4.0
-Migration guides for upgrading from previous releases of the Spring Framework are now
-provided as a Wiki page. For details please refer to
-https://github.com/spring-projects/spring-framework/wiki/Migrating-from-earlier-versions-of-the-spring-framework
-
-
-
-
-
-[[classic-spring]]
-== Classic Spring Usage
-This appendix discusses some classic Spring usage patterns as a reference for developers
-maintaining legacy Spring applications. These usage patterns no longer reflect the
-recommended way of using these features and the current recommended usage is covered in
-the respective sections of the reference manual.
-
-
-
-
-[[classic-spring-orm]]
-=== Classic ORM usage
-This section documents the classic usage patterns that you might encounter in a legacy
-Spring application. For the currently recommended usage patterns, please refer to the
-<> chapter.
-
-
-
-[[classic-spring-hibernate]]
-==== Hibernate
-For the currently recommended usage patterns for Hibernate see <>
-
-
-[[orm-hibernate-template]]
-===== the HibernateTemplate
-
-The basic programming model for templating looks as follows, for methods that can be
-part of any custom data access object or business service. There are no restrictions on
-the implementation of the surrounding object at all, it just needs to provide a
-Hibernate `SessionFactory`. It can get the latter from anywhere, but preferably as bean
-reference from a Spring IoC container - via a simple `setSessionFactory(..)` bean
-property setter. The following snippets show a DAO definition in a Spring container,
-referencing the above defined `SessionFactory`, and an example for a DAO method
-implementation.
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-
-----
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public class ProductDaoImpl implements ProductDao {
-
- private HibernateTemplate hibernateTemplate;
-
- public void setSessionFactory(SessionFactory sessionFactory) {
- this.hibernateTemplate = new HibernateTemplate(sessionFactory);
- }
-
- public Collection loadProductsByCategory(String category) throws DataAccessException {
- return this.hibernateTemplate.find("from test.Product product where product.category=?", category);
- }
- }
-----
-
-The `HibernateTemplate` class provides many methods that mirror the methods exposed on
-the Hibernate `Session` interface, in addition to a number of convenience methods such
-as the one shown above. If you need access to the `Session` to invoke methods that are
-not exposed on the `HibernateTemplate`, you can always drop down to a callback-based
-approach like so.
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public class ProductDaoImpl implements ProductDao {
-
- private HibernateTemplate hibernateTemplate;
-
- public void setSessionFactory(SessionFactory sessionFactory) {
- this.hibernateTemplate = new HibernateTemplate(sessionFactory);
- }
-
- public Collection loadProductsByCategory(final String category) throws DataAccessException {
- return this.hibernateTemplate.execute(new HibernateCallback() {
- public Object doInHibernate(Session session) {
- Criteria criteria = session.createCriteria(Product.class);
- criteria.add(Expression.eq("category", category));
- criteria.setMaxResults(6);
- return criteria.list();
- }
- };
- }
-
- }
-----
-
-A callback implementation effectively can be used for any Hibernate data access.
-`HibernateTemplate` will ensure that `Session` instances are properly opened and closed,
-and automatically participate in transactions. The template instances are thread-safe
-and reusable, they can thus be kept as instance variables of the surrounding class. For
-simple single step actions like a single find, load, saveOrUpdate, or delete call,
-`HibernateTemplate` offers alternative convenience methods that can replace such one
-line callback implementations. Furthermore, Spring provides a convenient
-`HibernateDaoSupport` base class that provides a `setSessionFactory(..)` method for
-receiving a `SessionFactory`, and `getSessionFactory()` and `getHibernateTemplate()` for
-use by subclasses. In combination, this allows for very simple DAO implementations for
-typical requirements:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public class ProductDaoImpl extends HibernateDaoSupport implements ProductDao {
-
- public Collection loadProductsByCategory(String category) throws DataAccessException {
- return this.getHibernateTemplate().find(
- "from test.Product product where product.category=?", category);
- }
-
- }
-----
-
-
-[[orm-hibernate-daos]]
-===== Implementing Spring-based DAOs without callbacks
-As alternative to using Spring's `HibernateTemplate` to implement DAOs, data access code
-can also be written in a more traditional fashion, without wrapping the Hibernate access
-code in a callback, while still respecting and participating in Spring's generic
-`DataAccessException` hierarchy. The `HibernateDaoSupport` base class offers methods to
-access the current transactional `Session` and to convert exceptions in such a scenario;
-similar methods are also available as static helpers on the `SessionFactoryUtils` class.
-Note that such code will usually pass ' `false`' as the value of the `getSession(..)`
-methods ' `allowCreate`' argument, to enforce running within a transaction (which avoids
-the need to close the returned `Session`, as its lifecycle is managed by the
-transaction).
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public class HibernateProductDao extends HibernateDaoSupport implements ProductDao {
-
- public Collection loadProductsByCategory(String category) throws DataAccessException, MyException {
- Session session = getSession(false);
- try {
- Query query = session.createQuery("from test.Product product where product.category=?");
- query.setString(0, category);
- List result = query.list();
- if (result == null) {
- throw new MyException("No search results.");
- }
- return result;
- }
- catch (HibernateException ex) {
- throw convertHibernateAccessException(ex);
- }
- }
- }
-----
-
-The advantage of such direct Hibernate access code is that it allows __any__ checked
-application exception to be thrown within the data access code; contrast this to the
-`HibernateTemplate` class which is restricted to throwing only unchecked exceptions
-within the callback. Note that you can often defer the corresponding checks and the
-throwing of application exceptions to after the callback, which still allows working
-with `HibernateTemplate`. In general, the `HibernateTemplate` class' convenience methods
-are simpler and more convenient for many scenarios.
-
-
-
-[[classic-spring-jdo]]
-==== JDO
-For the currently recommended usage patterns for JDO see <>
-
-
-[[orm-jdo-template]]
-===== JdoTemplate and `JdoDaoSupport`
-
-Each JDO-based DAO will then receive the `PersistenceManagerFactory` through dependency
-injection. Such a DAO could be coded against plain JDO API, working with the given
-`PersistenceManagerFactory`, but will usually rather be used with the Spring Framework's
-`JdoTemplate`:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-
-----
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public class ProductDaoImpl implements ProductDao {
-
- private JdoTemplate jdoTemplate;
-
- public void setPersistenceManagerFactory(PersistenceManagerFactory pmf) {
- this.jdoTemplate = new JdoTemplate(pmf);
- }
-
- public Collection loadProductsByCategory(final String category) throws DataAccessException {
- return (Collection) this.jdoTemplate.execute(new JdoCallback() {
- public Object doInJdo(PersistenceManager pm) throws JDOException {
- Query query = pm.newQuery(Product.class, "category = pCategory");
- query.declareParameters("String pCategory");
- List result = query.execute(category);
- // do some further stuff with the result list
- return result;
- }
- });
- }
-
- }
-----
-
-A callback implementation can effectively be used for any JDO data access. `JdoTemplate`
-will ensure that `PersistenceManager` s are properly opened and closed, and
-automatically participate in transactions. The template instances are thread-safe and
-reusable, they can thus be kept as instance variables of the surrounding class. For
-simple single-step actions such as a single `find`, `load`, `makePersistent`, or
-`delete` call, `JdoTemplate` offers alternative convenience methods that can replace
-such one line callback implementations. Furthermore, Spring provides a convenient
-`JdoDaoSupport` base class that provides a `setPersistenceManagerFactory(..)` method for
-receiving a `PersistenceManagerFactory`, and `getPersistenceManagerFactory()` and
-`getJdoTemplate()` for use by subclasses. In combination, this allows for very simple
-DAO implementations for typical requirements:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public class ProductDaoImpl extends JdoDaoSupport implements ProductDao {
-
- public Collection loadProductsByCategory(String category) throws DataAccessException {
- return getJdoTemplate().find(Product.class,
- "category = pCategory", "String category", new Object[] {category});
- }
-
- }
-----
-
-As alternative to working with Spring's `JdoTemplate`, you can also code Spring-based
-DAOs at the JDO API level, explicitly opening and closing a `PersistenceManager`. As
-elaborated in the corresponding Hibernate section, the main advantage of this approach
-is that your data access code is able to throw checked exceptions. `JdoDaoSupport`
-offers a variety of support methods for this scenario, for fetching and releasing a
-transactional `PersistenceManager` as well as for converting exceptions.
-
-
-
-[[classic-spring-jpa]]
-==== JPA
-For the currently recommended usage patterns for JPA see <>
-
-
-[[orm-jpa-template]]
-===== JpaTemplate and `JpaDaoSupport`
-
-Each JPA-based DAO will then receive a `EntityManagerFactory` via dependency injection.
-Such a DAO can be coded against plain JPA and work with the given `EntityManagerFactory`
-or through Spring's `JpaTemplate`:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-
-----
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public class JpaProductDao implements ProductDao {
-
- private JpaTemplate jpaTemplate;
-
- public void setEntityManagerFactory(EntityManagerFactory emf) {
- this.jpaTemplate = new JpaTemplate(emf);
- }
-
- public Collection loadProductsByCategory(final String category) throws DataAccessException {
- return (Collection) this.jpaTemplate.execute(new JpaCallback() {
- public Object doInJpa(EntityManager em) throws PersistenceException {
- Query query = em.createQuery("from Product as p where p.category = :category");
- query.setParameter("category", category);
- List result = query.getResultList();
- // do some further processing with the result list
- return result;
- }
- });
- }
-
- }
-----
-
-The `JpaCallback` implementation allows any type of JPA data access. The `JpaTemplate`
-will ensure that `EntityManager` s are properly opened and closed and automatically
-participate in transactions. Moreover, the `JpaTemplate` properly handles exceptions,
-making sure resources are cleaned up and the appropriate transactions rolled back. The
-template instances are thread-safe and reusable and they can be kept as instance
-variable of the enclosing class. Note that `JpaTemplate` offers single-step actions such
-as find, load, merge, etc along with alternative convenience methods that can replace
-one line callback implementations.
-
-Furthermore, Spring provides a convenient `JpaDaoSupport` base class that provides the
-`get/setEntityManagerFactory` and `getJpaTemplate()` to be used by subclasses:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public class ProductDaoImpl extends JpaDaoSupport implements ProductDao {
-
- public Collection loadProductsByCategory(String category) throws DataAccessException {
- Map params = new HashMap();
- params.put("category", category);
- return getJpaTemplate().findByNamedParams("from Product as p where p.category = :category", params);
- }
-
- }
-----
-
-Besides working with Spring's `JpaTemplate`, one can also code Spring-based DAOs against
-the JPA, doing one's own explicit `EntityManager` handling. As also elaborated in the
-corresponding Hibernate section, the main advantage of this approach is that your data
-access code is able to throw checked exceptions. `JpaDaoSupport` offers a variety of
-support methods for this scenario, for retrieving and releasing a transaction
-`EntityManager`, as well as for converting exceptions.
-
-__JpaTemplate mainly exists as a sibling of JdoTemplate and HibernateTemplate, offering
-the same style for people used to it.__
-
-
-
-
-[[clasic-spring-mvc]]
-=== Classic Spring MVC
-...
-
-
-
-
-[[classic-spring-jms]]
-=== JMS Usage
-
-One of the benefits of Spring's JMS support is to shield the user from differences
-between the JMS 1.0.2 and 1.1 APIs. (For a description of the differences between the
-two APIs see sidebar on Domain Unification). Since it is now common to encounter only
-the JMS 1.1 API the use of classes that are based on the JMS 1.0.2 API has been
-deprecated in Spring 3.0. This section describes Spring JMS support for the JMS 1.0.2
-deprecated classes.
-
-.Domain Unification
-****
-There are two major releases of the JMS specification, 1.0.2 and 1.1.
-
-JMS 1.0.2 defined two types of messaging domains, point-to-point (Queues) and
-publish/subscribe (Topics). The 1.0.2 API reflected these two messaging domains by
-providing a parallel class hierarchy for each domain. As a result, a client application
-became domain specific in its use of the JMS API. JMS 1.1 introduced the concept of
-domain unification that minimized both the functional differences and client API
-differences between the two domains. As an example of a functional difference that was
-removed, if you use a JMS 1.1 provider you can transactionally consume a message from
-one domain and produce a message on the other using the same `Session`.
-
-[NOTE]
-====
-The JMS 1.1 specification was released in April 2002 and incorporated as part of J2EE
-1.4 in November 2003. As a result, common J2EE 1.3 application servers which are still
-in widespread use (such as BEA WebLogic 8.1 and IBM WebSphere 5.1) are based on JMS
-1.0.2.
-====
-****
-
-
-
-[[classic-spring-jms-template]]
-==== JmsTemplate
-Located in the package `org.springframework.jms.core` the class `JmsTemplate102`
-provides all of the features of the `JmsTemplate` described the JMS chapter, but is
-based on the JMS 1.0.2 API instead of the JMS 1.1 API. As a consequence, if you are
-using JmsTemplate102 you need to set the boolean property `pubSubDomain` to configure
-the `JmsTemplate` with knowledge of what JMS domain is being used. By default the value
-of this property is false, indicating that the point-to-point domain, Queues, will be
-used.
-
-
-
-[[classic-spring-aysnc-messages]]
-==== Asynchronous Message Reception
-<> are used in
-conjunction with Spring's <> to support
-asynchronous message reception by exposing almost any class as a Message-driven POJO. If
-you are using the JMS 1.0.2 API, you will want to use the 1.0.2 specific classes such as
-`MessageListenerAdapter102`, `SimpleMessageListenerContainer102`, and
-`DefaultMessageListenerContainer102`. These classes provide the same functionality as
-the JMS 1.1 based counterparts but rely only on the JMS 1.0.2 API.
-
-
-
-[[classic-spring-jms-connections]]
-==== Connections
-The `ConnectionFactory` interface is part of the JMS specification and serves as the
-entry point for working with JMS. Spring provides an implementation of the
-`ConnectionFactory` interface, `SingleConnectionFactory102`, based on the JMS 1.0.2 API
-that will return the same `Connection` on all `createConnection()` calls and ignore
-calls to `close()`. You will need to set the boolean property `pubSubDomain` to indicate
-which messaging domain is used as `SingleConnectionFactory102` will always explicitly
-differentiate between a `javax.jms.QueueConnection` and a `javax.jmsTopicConnection`.
-
-
-
-[[classic-spring-jms-tx-management]]
-==== Transaction Management
-In a JMS 1.0.2 environment the class `JmsTransactionManager102` provides support for
-managing JMS transactions for a single Connection Factory. Please refer to the reference
-documentation on <> for more information on this
-functionality.
-
-
-
-
-
-[[classic-aop-spring]]
-== Classic Spring AOP Usage
-In this appendix we discuss the lower-level Spring AOP APIs and the AOP support used in
-Spring 1.2 applications. For new applications, we recommend the use of the Spring 2.0
-AOP support described in the <> chapter, but when working with existing
-applications, or when reading books and articles, you may come across Spring 1.2 style
-examples. Spring 2.0 is fully backwards compatible with Spring 1.2 and everything
-described in this appendix is fully supported in Spring 2.0.
-
-
-
-
-[[classic-aop-api-pointcuts]]
-=== Pointcut API in Spring
-Let's look at how Spring handles the crucial pointcut concept.
-
-
-
-[[classic-aop-api-concepts]]
-==== Concepts
-Spring's pointcut model enables pointcut reuse independent of advice types. It's
-possible to target different advice using the same pointcut.
-
-The `org.springframework.aop.Pointcut` interface is the central interface, used to
-target advices to particular classes and methods. The complete interface is shown below:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public interface Pointcut {
-
- ClassFilter getClassFilter();
-
- MethodMatcher getMethodMatcher();
-
- }
-----
-
-Splitting the `Pointcut` interface into two parts allows reuse of class and method
-matching parts, and fine-grained composition operations (such as performing a "union"
-with another method matcher).
-
-The `ClassFilter` interface is used to restrict the pointcut to a given set of target
-classes. If the `matches()` method always returns true, all target classes will be
-matched:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public interface ClassFilter {
-
- boolean matches(Class clazz);
-
- }
-----
-
-The `MethodMatcher` interface is normally more important. The complete interface is
-shown below:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public interface MethodMatcher {
-
- boolean matches(Method m, Class targetClass);
-
- boolean isRuntime();
-
- boolean matches(Method m, Class targetClass, Object[] args);
-
- }
-----
-
-The `matches(Method, Class)` method is used to test whether this pointcut will ever
-match a given method on a target class. This evaluation can be performed when an AOP
-proxy is created, to avoid the need for a test on every method invocation. If the
-2-argument matches method returns true for a given method, and the `isRuntime()` method
-for the MethodMatcher returns true, the 3-argument matches method will be invoked on
-every method invocation. This enables a pointcut to look at the arguments passed to the
-method invocation immediately before the target advice is to execute.
-
-Most MethodMatchers are static, meaning that their `isRuntime()` method returns false.
-In this case, the 3-argument matches method will never be invoked.
-
-[TIP]
-====
-
-If possible, try to make pointcuts static, allowing the AOP framework to cache the
-results of pointcut evaluation when an AOP proxy is created.
-====
-
-
-
-[[classic-aop-api-pointcut-ops]]
-==== Operations on pointcuts
-Spring supports operations on pointcuts: notably, __union__ and __intersection__.
-
-* Union means the methods that either pointcut matches.
-* Intersection means the methods that both pointcuts match.
-* Union is usually more useful.
-* Pointcuts can be composed using the static methods in the
- __org.springframework.aop.support.Pointcuts__ class, or using the
- __ComposablePointcut__ class in the same package. However, using AspectJ pointcut
- expressions is usually a simpler approach.
-
-
-
-[[classic-aop-api-pointcuts-aspectj]]
-==== AspectJ expression pointcuts
-Since 2.0, the most important type of pointcut used by Spring is
-`org.springframework.aop.aspectj.AspectJExpressionPointcut`. This is a pointcut that
-uses an AspectJ supplied library to parse an AspectJ pointcut expression string.
-
-See the previous chapter for a discussion of supported AspectJ pointcut primitives.
-
-
-
-[[classic-aop-api-pointcuts-impls]]
-==== Convenience pointcut implementations
-Spring provides several convenient pointcut implementations. Some can be used out of the
-box; others are intended to be subclassed in application-specific pointcuts.
-
-
-[[classic-aop-api-pointcuts-static]]
-===== Static pointcuts
-Static pointcuts are based on method and target class, and cannot take into account the
-method's arguments. Static pointcuts are sufficient - __and best__ - for most usages.
-It's possible for Spring to evaluate a static pointcut only once, when a method is first
-invoked: after that, there is no need to evaluate the pointcut again with each method
-invocation.
-
-Let's consider some static pointcut implementations included with Spring.
-
-[[classic-aop-api-pointcuts-regex]]
-====== Regular expression pointcuts
-One obvious way to specify static pointcuts is regular expressions. Several AOP
-frameworks besides Spring make this possible.
-`org.springframework.aop.support.Perl5RegexpMethodPointcut` is a generic regular
-expression pointcut, using Perl 5 regular expression syntax. The
-`Perl5RegexpMethodPointcut` class depends on Jakarta ORO for regular expression
-matching. Spring also provides the `JdkRegexpMethodPointcut` class that uses the regular
-expression support in JDK 1.4+.
-
-Using the `Perl5RegexpMethodPointcut` class, you can provide a list of pattern Strings.
-If any of these is a match, the pointcut will evaluate to true. (So the result is
-effectively the union of these pointcuts.)
-
-The usage is shown below:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
- .*set.*
- .*absquatulate
-
-
-
-----
-
-Spring provides a convenience class, `RegexpMethodPointcutAdvisor`, that allows us to
-also reference an Advice (remember that an Advice can be an interceptor, before advice,
-throws advice etc.). Behind the scenes, Spring will use a `JdkRegexpMethodPointcut`.
-Using `RegexpMethodPointcutAdvisor` simplifies wiring, as the one bean encapsulates both
-pointcut and advice, as shown below:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
- .*set.*
- .*absquatulate
-
-
-
-----
-
-__RegexpMethodPointcutAdvisor__ can be used with any Advice type.
-
-[[classic-aop-api-pointcuts-attribute-driven]]
-====== Attribute-driven pointcuts
-An important type of static pointcut is a __metadata-driven__ pointcut. This uses the
-values of metadata attributes: typically, source-level metadata.
-
-
-[[classic-aop-api-pointcuts-dynamic]]
-===== Dynamic pointcuts
-Dynamic pointcuts are costlier to evaluate than static pointcuts. They take into account
-method__arguments__, as well as static information. This means that they must be
-evaluated with every method invocation; the result cannot be cached, as arguments will
-vary.
-
-The main example is the `control flow` pointcut.
-
-[[classic-aop-api-pointcuts-cflow]]
-====== Control flow pointcuts
-Spring control flow pointcuts are conceptually similar to AspectJ __cflow__ pointcuts,
-although less powerful. (There is currently no way to specify that a pointcut executes
-below a join point matched by another pointcut.) A control flow pointcut matches the
-current call stack. For example, it might fire if the join point was invoked by a method
-in the `com.mycompany.web` package, or by the `SomeCaller` class. Control flow pointcuts
-are specified using the `org.springframework.aop.support.ControlFlowPointcut` class.
-[NOTE]
-====
-Control flow pointcuts are significantly more expensive to evaluate at runtime than even
-other dynamic pointcuts. In Java 1.4, the cost is about 5 times that of other dynamic
-pointcuts.
-====
-
-
-
-[[classic-aop-api-pointcuts-superclasses]]
-==== Pointcut superclasses
-Spring provides useful pointcut superclasses to help you to implement your own pointcuts.
-
-Because static pointcuts are most useful, you'll probably subclass
-StaticMethodMatcherPointcut, as shown below. This requires implementing just one
-abstract method (although it's possible to override other methods to customize behavior):
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- class TestStaticPointcut extends StaticMethodMatcherPointcut {
-
- public boolean matches(Method m, Class targetClass) {
- // return true if custom criteria match
- }
-
- }
-----
-
-There are also superclasses for dynamic pointcuts.
-
-You can use custom pointcuts with any advice type in Spring 1.0 RC2 and above.
-
-
-
-[[classic-aop-api-pointcuts-custom]]
-==== Custom pointcuts
-Because pointcuts in Spring AOP are Java classes, rather than language features (as in
-AspectJ) it's possible to declare custom pointcuts, whether static or dynamic. Custom
-pointcuts in Spring can be arbitrarily complex. However, using the AspectJ pointcut
-expression language is recommended if possible.
-
-[NOTE]
-====
-Later versions of Spring may offer support for "semantic pointcuts" as offered by JAC:
-for example, "all methods that change instance variables in the target object."
-====
-
-
-
-
-[[classic-aop-api-advice]]
-=== Advice API in Spring
-Let's now look at how Spring AOP handles advice.
-
-
-
-[[classic-aop-api-advice-lifecycle]]
-==== Advice lifecycles
-Each advice is a Spring bean. An advice instance can be shared across all advised
-objects, or unique to each advised object. This corresponds to __per-class__ or
-__per-instance__ advice.
-
-Per-class advice is used most often. It is appropriate for generic advice such as
-transaction advisors. These do not depend on the state of the proxied object or add new
-state; they merely act on the method and arguments.
-
-Per-instance advice is appropriate for introductions, to support mixins. In this case,
-the advice adds state to the proxied object.
-
-It's possible to use a mix of shared and per-instance advice in the same AOP proxy.
-
-
-
-[[classic-aop-api-advice-types]]
-==== Advice types in Spring
-Spring provides several advice types out of the box, and is extensible to support
-arbitrary advice types. Let us look at the basic concepts and standard advice types.
-
-
-[[classic-aop-api-advice-around]]
-===== Interception around advice
-The most fundamental advice type in Spring is __interception around advice__.
-
-Spring is compliant with the AOP Alliance interface for around advice using method
-interception. MethodInterceptors implementing around advice should implement the
-following interface:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public interface MethodInterceptor extends Interceptor {
-
- Object invoke(MethodInvocation invocation) throws Throwable;
-
- }
-----
-
-The `MethodInvocation` argument to the `invoke()` method exposes the method being
-invoked; the target join point; the AOP proxy; and the arguments to the method. The
-`invoke()` method should return the invocation's result: the return value of the join
-point.
-
-A simple `MethodInterceptor` implementation looks as follows:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public class DebugInterceptor implements MethodInterceptor {
-
- public Object invoke(MethodInvocation invocation) throws Throwable {
- System.out.println("Before: invocation=[" + invocation + "]");
- Object rval = invocation.proceed();
- System.out.println("Invocation returned");
- return rval;
- }
-
- }
-----
-
-Note the call to the MethodInvocation's `proceed()` method. This proceeds down the
-interceptor chain towards the join point. Most interceptors will invoke this method, and
-return its return value. However, a MethodInterceptor, like any around advice, can
-return a different value or throw an exception rather than invoke the proceed method.
-However, you don't want to do this without good reason!
-
-[NOTE]
-====
-MethodInterceptors offer interoperability with other AOP Alliance-compliant AOP
-implementations. The other advice types discussed in the remainder of this section
-implement common AOP concepts, but in a Spring-specific way. While there is an advantage
-in using the most specific advice type, stick with MethodInterceptor around advice if
-you are likely to want to run the aspect in another AOP framework. Note that pointcuts
-are not currently interoperable between frameworks, and the AOP Alliance does not
-currently define pointcut interfaces.
-====
-
-
-[[classic-aop-api-advice-before]]
-===== Before advice
-A simpler advice type is a __before advice__. This does not need a `MethodInvocation`
-object, since it will only be called before entering the method.
-
-The main advantage of a before advice is that there is no need to invoke the `proceed()`
-method, and therefore no possibility of inadvertently failing to proceed down the
-interceptor chain.
-
-The `MethodBeforeAdvice` interface is shown below. (Spring's API design would allow for
-field before advice, although the usual objects apply to field interception and it's
-unlikely that Spring will ever implement it).
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public interface MethodBeforeAdvice extends BeforeAdvice {
-
- void before(Method m, Object[] args, Object target) throws Throwable;
-
- }
-----
-
-Note the return type is `void`. Before advice can insert custom behavior before the join
-point executes, but cannot change the return value. If a before advice throws an
-exception, this will abort further execution of the interceptor chain. The exception
-will propagate back up the interceptor chain. If it is unchecked, or on the signature of
-the invoked method, it will be passed directly to the client; otherwise it will be
-wrapped in an unchecked exception by the AOP proxy.
-
-An example of a before advice in Spring, which counts all method invocations:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public class CountingBeforeAdvice implements MethodBeforeAdvice {
-
- private int count;
-
- public void before(Method m, Object[] args, Object target) throws Throwable {
- ++count;
- }
-
- public int getCount() {
- return count;
- }
- }
-----
-
-[TIP]
-====
-
-Before advice can be used with any pointcut.
-====
-
-
-[[classic-aop-api-advice-throws]]
-===== Throws advice
-__Throws advice__ is invoked after the return of the join point if the join point threw
-an exception. Spring offers typed throws advice. Note that this means that the
-`org.springframework.aop.ThrowsAdvice` interface does not contain any methods: It is a
-tag interface identifying that the given object implements one or more typed throws
-advice methods. These should be in the form of:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- afterThrowing([Method, args, target], subclassOfThrowable)
-----
-
-Only the last argument is required. The method signatures may have either one or four
-arguments, depending on whether the advice method is interested in the method and
-arguments. The following classes are examples of throws advice.
-
-The advice below is invoked if a `RemoteException` is thrown (including subclasses):
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public class RemoteThrowsAdvice implements ThrowsAdvice {
-
- public void afterThrowing(RemoteException ex) throws Throwable {
- // Do something with remote exception
- }
-
- }
-----
-
-The following advice is invoked if a `ServletException` is thrown. Unlike the above
-advice, it declares 4 arguments, so that it has access to the invoked method, method
-arguments and target object:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public class ServletThrowsAdviceWithArguments implements ThrowsAdvice {
-
- public void afterThrowing(Method m, Object[] args, Object target, ServletException ex) {
- // Do something with all arguments
- }
-
- }
-----
-
-The final example illustrates how these two methods could be used in a single class,
-which handles both `RemoteException` and `ServletException`. Any number of throws advice
-methods can be combined in a single class.
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public static class CombinedThrowsAdvice implements ThrowsAdvice {
-
- public void afterThrowing(RemoteException ex) throws Throwable {
- // Do something with remote exception
- }
-
- public void afterThrowing(Method m, Object[] args, Object target, ServletException ex) {
- // Do something with all arguments
- }
- }
-----
-
-__Note:__ If a throws-advice method throws an exception itself, it will override the
-original exception (i.e. change the exception thrown to the user). The overriding
-exception will typically be a RuntimeException; this is compatible with any method
-signature. However, if a throws-advice method throws a checked exception, it will have
-to match the declared exceptions of the target method and is hence to some degree
-coupled to specific target method signatures. __Do not throw an undeclared checked
-exception that is incompatible with the target method's signature!__
-
-[TIP]
-====
-
-Throws advice can be used with any pointcut.
-====
-
-
-[[classic-aop-api-advice-after-returning]]
-===== After Returning advice
-An after returning advice in Spring must implement the
-__org.springframework.aop.AfterReturningAdvice__ interface, shown below:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public interface AfterReturningAdvice extends Advice {
-
- void afterReturning(Object returnValue, Method m, Object[] args,
- Object target) throws Throwable;
-
- }
-----
-
-An after returning advice has access to the return value (which it cannot modify),
-invoked method, methods arguments and target.
-
-The following after returning advice counts all successful method invocations that have
-not thrown exceptions:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public class CountingAfterReturningAdvice implements AfterReturningAdvice {
-
- private int count;
-
- public void afterReturning(Object returnValue, Method m, Object[] args,
- Object target) throws Throwable {
- ++count;
- }
-
- public int getCount() {
- return count;
- }
-
- }
-----
-
-This advice doesn't change the execution path. If it throws an exception, this will be
-thrown up the interceptor chain instead of the return value.
-
-[TIP]
-====
-
-After returning advice can be used with any pointcut.
-====
-
-
-[[classic-aop-api-advice-introduction]]
-===== Introduction advice
-Spring treats introduction advice as a special kind of interception advice.
-
-Introduction requires an `IntroductionAdvisor`, and an `IntroductionInterceptor`,
-implementing the following interface:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public interface IntroductionInterceptor extends MethodInterceptor {
-
- boolean implementsInterface(Class intf);
-
- }
-----
-
-The `invoke()` method inherited from the AOP Alliance `MethodInterceptor` interface must
-implement the introduction: that is, if the invoked method is on an introduced
-interface, the introduction interceptor is responsible for handling the method call - it
-cannot invoke `proceed()`.
-
-Introduction advice cannot be used with any pointcut, as it applies only at class,
-rather than method, level. You can only use introduction advice with the
-`IntroductionAdvisor`, which has the following methods:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public interface IntroductionAdvisor extends Advisor, IntroductionInfo {
-
- ClassFilter getClassFilter();
-
- void validateInterfaces() throws IllegalArgumentException;
-
- }
-
- public interface IntroductionInfo {
-
- Class[] getInterfaces();
-
- }
-----
-
-There is no `MethodMatcher`, and hence no `Pointcut`, associated with introduction
-advice. Only class filtering is logical.
-
-The `getInterfaces()` method returns the interfaces introduced by this advisor.
-
-The `validateInterfaces()` method is used internally to see whether or not the
-introduced interfaces can be implemented by the configured `IntroductionInterceptor`.
-
-Let's look at a simple example from the Spring test suite. Let's suppose we want to
-introduce the following interface to one or more objects:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public interface Lockable {
-
- void lock();
-
- void unlock();
-
- boolean locked();
-
- }
-----
-
-This illustrates a __mixin__. We want to be able to cast advised objects to Lockable,
-whatever their type, and call lock and unlock methods. If we call the lock() method, we
-want all setter methods to throw a `LockedException`. Thus we can add an aspect that
-provides the ability to make objects immutable, without them having any knowledge of it:
-a good example of AOP.
-
-Firstly, we'll need an `IntroductionInterceptor` that does the heavy lifting. In this
-case, we extend the `org.springframework.aop.support.DelegatingIntroductionInterceptor`
-convenience class. We could implement IntroductionInterceptor directly, but using
-`DelegatingIntroductionInterceptor` is best for most cases.
-
-The `DelegatingIntroductionInterceptor` is designed to delegate an introduction to an
-actual implementation of the introduced interface(s), concealing the use of interception
-to do so. The delegate can be set to any object using a constructor argument; the
-default delegate (when the no-arg constructor is used) is this. Thus in the example
-below, the delegate is the `LockMixin` subclass of `DelegatingIntroductionInterceptor`.
-Given a delegate (by default itself), a `DelegatingIntroductionInterceptor` instance
-looks for all interfaces implemented by the delegate (other than
-IntroductionInterceptor), and will support introductions against any of them. It's
-possible for subclasses such as `LockMixin` to call the `suppressInterface(Class intf)`
-method to suppress interfaces that should not be exposed. However, no matter how many
-interfaces an `IntroductionInterceptor` is prepared to support, the
-`IntroductionAdvisor` used will control which interfaces are actually exposed. An
-introduced interface will conceal any implementation of the same interface by the target.
-
-Thus LockMixin subclasses `DelegatingIntroductionInterceptor` and implements Lockable
-itself. The superclass automatically picks up that Lockable can be supported for
-introduction, so we don't need to specify that. We could introduce any number of
-interfaces in this way.
-
-Note the use of the `locked` instance variable. This effectively adds additional state
-to that held in the target object.
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public class LockMixin extends DelegatingIntroductionInterceptor implements Lockable {
-
- private boolean locked;
-
- public void lock() {
- this.locked = true;
- }
-
- public void unlock() {
- this.locked = false;
- }
-
- public boolean locked() {
- return this.locked;
- }
-
- public Object invoke(MethodInvocation invocation) throws Throwable {
- if (locked() && invocation.getMethod().getName().indexOf("set") == 0) {
- throw new LockedException();
- }
- return super.invoke(invocation);
- }
-
- }
-----
-
-Often it isn't necessary to override the `invoke()` method: the
-`DelegatingIntroductionInterceptor` implementation - which calls the delegate method if
-the method is introduced, otherwise proceeds towards the join point - is usually
-sufficient. In the present case, we need to add a check: no setter method can be invoked
-if in locked mode.
-
-The introduction advisor required is simple. All it needs to do is hold a distinct
-`LockMixin` instance, and specify the introduced interfaces - in this case, just
-`Lockable`. A more complex example might take a reference to the introduction
-interceptor (which would be defined as a prototype): in this case, there's no
-configuration relevant for a `LockMixin`, so we simply create it using `new`.
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- public class LockMixinAdvisor extends DefaultIntroductionAdvisor {
-
- public LockMixinAdvisor() {
- super(new LockMixin(), Lockable.class);
- }
-
- }
-----
-
-We can apply this advisor very simply: it requires no configuration. (However, it __is__
-necessary: It's impossible to use an `IntroductionInterceptor` without an
-__IntroductionAdvisor__.) As usual with introductions, the advisor must be per-instance,
-as it is stateful. We need a different instance of `LockMixinAdvisor`, and hence
-`LockMixin`, for each advised object. The advisor comprises part of the advised object's
-state.
-
-We can apply this advisor programmatically, using the `Advised.addAdvisor()` method, or
-(the recommended way) in XML configuration, like any other advisor. All proxy creation
-choices discussed below, including "auto proxy creators," correctly handle introductions
-and stateful mixins.
-
-
-
-
-[[classic-aop-api-advisor]]
-=== Advisor API in Spring
-In Spring, an Advisor is an aspect that contains just a single advice object associated
-with a pointcut expression.
-
-Apart from the special case of introductions, any advisor can be used with any advice.
-`org.springframework.aop.support.DefaultPointcutAdvisor` is the most commonly used
-advisor class. For example, it can be used with a `MethodInterceptor`, `BeforeAdvice` or
-`ThrowsAdvice`.
-
-It is possible to mix advisor and advice types in Spring in the same AOP proxy. For
-example, you could use a interception around advice, throws advice and before advice in
-one proxy configuration: Spring will automatically create the necessary interceptor
-chain.
-
-
-
-
-[[classic-aop-pfb]]
-=== Using the ProxyFactoryBean to create AOP proxies
-If you're using the Spring IoC container (an ApplicationContext or BeanFactory) for your
-business objects - and you should be! - you will want to use one of Spring's AOP
-FactoryBeans. (Remember that a factory bean introduces a layer of indirection, enabling
-it to create objects of a different type.)
-
-[NOTE]
-====
-The Spring 2.0 AOP support also uses factory beans under the covers.
-====
-
-The basic way to create an AOP proxy in Spring is to use the
-__org.springframework.aop.framework.ProxyFactoryBean__. This gives complete control over
-the pointcuts and advice that will apply, and their ordering. However, there are simpler
-options that are preferable if you don't need such control.
-
-
-
-[[classic-aop-pfb-1]]
-==== Basics
-The `ProxyFactoryBean`, like other Spring `FactoryBean` implementations, introduces a
-level of indirection. If you define a `ProxyFactoryBean` with name `foo`, what objects
-referencing `foo` see is not the `ProxyFactoryBean` instance itself, but an object
-created by the `ProxyFactoryBean`'s implementation of the `getObject()` method. This
-method will create an AOP proxy wrapping a target object.
-
-One of the most important benefits of using a `ProxyFactoryBean` or another IoC-aware
-class to create AOP proxies, is that it means that advices and pointcuts can also be
-managed by IoC. This is a powerful feature, enabling certain approaches that are hard to
-achieve with other AOP frameworks. For example, an advice may itself reference
-application objects (besides the target, which should be available in any AOP
-framework), benefiting from all the pluggability provided by Dependency Injection.
-
-
-
-[[classic-aop-pfb-2]]
-==== JavaBean properties
-In common with most `FactoryBean` implementations provided with Spring, the
-`ProxyFactoryBean` class is itself a JavaBean. Its properties are used to:
-
-* Specify the target you want to proxy.
-* Specify whether to use CGLIB (see below and also <>).
-
-Some key properties are inherited from `org.springframework.aop.framework.ProxyConfig`
-(the superclass for all AOP proxy factories in Spring). These key properties include:
-
-* `proxyTargetClass`: `true` if the target class is to be proxied, rather than the
- target class' interfaces. If this property value is set to `true`, then CGLIB proxies
- will be created (but see also below <>).
-* `optimize`: controls whether or not aggressive optimizations are applied to proxies
- __created via CGLIB__. One should not blithely use this setting unless one fully
- understands how the relevant AOP proxy handles optimization. This is currently used
- only for CGLIB proxies; it has no effect with JDK dynamic proxies.
-* `frozen`: if a proxy configuration is `frozen`, then changes to the configuration are
- no longer allowed. This is useful both as a slight optimization and for those cases
- when you don't want callers to be able to manipulate the proxy (via the `Advised`
- interface) after the proxy has been created. The default value of this property is
- `false`, so changes such as adding additional advice are allowed.
-* `exposeProxy`: determines whether or not the current proxy should be exposed in a
- `ThreadLocal` so that it can be accessed by the target. If a target needs to obtain
- the proxy and the `exposeProxy` property is set to `true`, the target can use the
- `AopContext.currentProxy()` method.
-* `aopProxyFactory`: the implementation of `AopProxyFactory` to use. Offers a way of
- customizing whether to use dynamic proxies, CGLIB or any other proxy strategy. The
- default implementation will choose dynamic proxies or CGLIB appropriately. There
- should be no need to use this property; it is intended to allow the addition of new
- proxy types in Spring 1.1.
-
-Other properties specific to `ProxyFactoryBean` include:
-
-* `proxyInterfaces`: array of String interface names. If this isn't supplied, a CGLIB
- proxy for the target class will be used (but see also below <>).
-* `interceptorNames`: String array of `Advisor`, interceptor or other advice names to
- apply. Ordering is significant, on a first come-first served basis. That is to say
- that the first interceptor in the list will be the first to be able to intercept the
- invocation.
-
-The names are bean names in the current factory, including bean names from ancestor
-factories. You can't mention bean references here since doing so would result in the
-`ProxyFactoryBean` ignoring the singleton setting of the advice.
-
-You can append an interceptor name with an asterisk ( `*`). This will result in the
-application of all advisor beans with names starting with the part before the asterisk
-to be applied. An example of using this feature can be found in <>.
-
-* singleton: whether or not the factory should return a single object, no matter how
- often the `getObject()` method is called. Several `FactoryBean` implementations offer
- such a method. The default value is `true`. If you want to use stateful advice - for
- example, for stateful mixins - use prototype advices along with a singleton value of
- `false`.
-
-
-
-[[classic-aop-pfb-proxy-types]]
-==== JDK- and CGLIB-based proxies
-This section serves as the definitive documentation on how the `ProxyFactoryBean`
-chooses to create one of either a JDK- and CGLIB-based proxy for a particular target
-object (that is to be proxied).
-
-[NOTE]
-====
-The behavior of the `ProxyFactoryBean` with regard to creating JDK- or CGLIB-based
-proxies changed between versions 1.2.x and 2.0 of Spring. The `ProxyFactoryBean` now
-exhibits similar semantics with regard to auto-detecting interfaces as those of the
-`TransactionProxyFactoryBean` class.
-====
-
-If the class of a target object that is to be proxied (hereafter simply referred to as
-the target class) doesn't implement any interfaces, then a CGLIB-based proxy will be
-created. This is the easiest scenario, because JDK proxies are interface based, and no
-interfaces means JDK proxying isn't even possible. One simply plugs in the target bean,
-and specifies the list of interceptors via the `interceptorNames` property. Note that a
-CGLIB-based proxy will be created even if the `proxyTargetClass` property of the
-`ProxyFactoryBean` has been set to `false`. (Obviously this makes no sense, and is best
-removed from the bean definition because it is at best redundant, and at worst
-confusing.)
-
-If the target class implements one (or more) interfaces, then the type of proxy that is
-created depends on the configuration of the `ProxyFactoryBean`.
-
-If the `proxyTargetClass` property of the `ProxyFactoryBean` has been set to `true`,
-then a CGLIB-based proxy will be created. This makes sense, and is in keeping with the
-principle of least surprise. Even if the `proxyInterfaces` property of the
-`ProxyFactoryBean` has been set to one or more fully qualified interface names, the fact
-that the `proxyTargetClass` property is set to `true` __will__ cause CGLIB-based
-proxying to be in effect.
-
-If the `proxyInterfaces` property of the `ProxyFactoryBean` has been set to one or more
-fully qualified interface names, then a JDK-based proxy will be created. The created
-proxy will implement all of the interfaces that were specified in the `proxyInterfaces`
-property; if the target class happens to implement a whole lot more interfaces than
-those specified in the `proxyInterfaces` property, that is all well and good but those
-additional interfaces will not be implemented by the returned proxy.
-
-If the `proxyInterfaces` property of the `ProxyFactoryBean` has __not__ been set, but
-the target class __does implement one (or more)__ interfaces, then the
-`ProxyFactoryBean` will auto-detect the fact that the target class does actually
-implement at least one interface, and a JDK-based proxy will be created. The interfaces
-that are actually proxied will be __all__ of the interfaces that the target class
-implements; in effect, this is the same as simply supplying a list of each and every
-interface that the target class implements to the `proxyInterfaces` property. However,
-it is significantly less work, and less prone to typos.
-
-
-
-[[classic-aop-api-proxying-intf]]
-==== Proxying interfaces
-Let's look at a simple example of `ProxyFactoryBean` in action. This example involves:
-
-* A __target bean__ that will be proxied. This is the "personTarget" bean definition in
- the example below.
-* An Advisor and an Interceptor used to provide advice.
-* An AOP proxy bean definition specifying the target object (the personTarget bean) and
- the interfaces to proxy, along with the advices to apply.
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
- Tony
- 51
-
-
-
- Custom string property value
-
-
-
-
-
-
- com.mycompany.Person
-
-
-
- myAdvisor
- debugInterceptor
-
-
-
-----
-
-Note that the `interceptorNames` property takes a list of String: the bean names of the
-interceptor or advisors in the current factory. Advisors, interceptors, before, after
-returning and throws advice objects can be used. The ordering of advisors is significant.
-
-[NOTE]
-====
-You might be wondering why the list doesn't hold bean references. The reason for this is
-that if the ProxyFactoryBean's singleton property is set to false, it must be able to
-return independent proxy instances. If any of the advisors is itself a prototype, an
-independent instance would need to be returned, so it's necessary to be able to obtain
-an instance of the prototype from the factory; holding a reference isn't sufficient.
-====
-
-The "person" bean definition above can be used in place of a Person implementation, as
-follows:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- Person person = (Person) factory.getBean("person");
-----
-
-Other beans in the same IoC context can express a strongly typed dependency on it, as
-with an ordinary Java object:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-----
-
-The `PersonUser` class in this example would expose a property of type Person. As far as
-it's concerned, the AOP proxy can be used transparently in place of a "real" person
-implementation. However, its class would be a dynamic proxy class. It would be possible
-to cast it to the `Advised` interface (discussed below).
-
-It's possible to conceal the distinction between target and proxy using an anonymous
-__inner bean__, as follows. Only the `ProxyFactoryBean` definition is different; the
-advice is included only for completeness:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
- Custom string property value
-
-
-
-
-
- com.mycompany.Person
-
-
-
- Tony
- 51
-
-
-
-
- myAdvisor
- debugInterceptor
-
-
-
-----
-
-This has the advantage that there's only one object of type `Person`: useful if we want
-to prevent users of the application context from obtaining a reference to the un-advised
-object, or need to avoid any ambiguity with Spring IoC __autowiring__. There's also
-arguably an advantage in that the ProxyFactoryBean definition is self-contained.
-However, there are times when being able to obtain the un-advised target from the
-factory might actually be an __advantage__: for example, in certain test scenarios.
-
-
-
-[[classic-aop-api-proxying-class]]
-==== Proxying classes
-What if you need to proxy a class, rather than one or more interfaces?
-
-Imagine that in our example above, there was no `Person` interface: we needed to advise
-a class called `Person` that didn't implement any business interface. In this case, you
-can configure Spring to use CGLIB proxying, rather than dynamic proxies. Simply set the
-`proxyTargetClass` property on the ProxyFactoryBean above to true. While it's best to
-program to interfaces, rather than classes, the ability to advise classes that don't
-implement interfaces can be useful when working with legacy code. (In general, Spring
-isn't prescriptive. While it makes it easy to apply good practices, it avoids forcing a
-particular approach.)
-
-If you want to, you can force the use of CGLIB in any case, even if you do have
-interfaces.
-
-CGLIB proxying works by generating a subclass of the target class at runtime. Spring
-configures this generated subclass to delegate method calls to the original target: the
-subclass is used to implement the __Decorator__ pattern, weaving in the advice.
-
-CGLIB proxying should generally be transparent to users. However, there are some issues
-to consider:
-
-* `Final` methods can't be advised, as they can't be overridden.
-* As of Spring 3.2 it is no longer required to add CGLIB to your project classpath.
- CGLIB classes have been repackaged under org.springframework and included directly in
- the spring-core JAR. This is both for user convenience as well as to avoid potential
- conflicts with other projects that have dependence on a differing version of CGLIB.
-
-There's little performance difference between CGLIB proxying and dynamic proxies. As of
-Spring 1.0, dynamic proxies are slightly faster. However, this may change in the future.
-Performance should not be a decisive consideration in this case.
-
-
-
-[[classic-aop-global-advisors]]
-==== Using 'global' advisors
-By appending an asterisk to an interceptor name, all advisors with bean names matching
-the part before the asterisk, will be added to the advisor chain. This can come in handy
-if you need to add a standard set of 'global' advisors:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
- global*
-
-
-
-
-
-
-----
-
-
-
-
-[[classic-aop-concise-proxy]]
-=== Concise proxy definitions
-Especially when defining transactional proxies, you may end up with many similar proxy
-definitions. The use of parent and child bean definitions, along with inner bean
-definitions, can result in much cleaner and more concise proxy definitions.
-
-First a parent, __template__, bean definition is created for the proxy:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
- PROPAGATION_REQUIRED
-
-
-
-----
-
-This will never be instantiated itself, so may actually be incomplete. Then each proxy
-which needs to be created is just a child bean definition, which wraps the target of the
-proxy as an inner bean definition, since the target will never be used on its own anyway.
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-----
-
-It is of course possible to override properties from the parent template, such as in
-this case, the transaction propagation settings:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-
- PROPAGATION_REQUIRED,readOnly
- PROPAGATION_REQUIRED,readOnly
- PROPAGATION_REQUIRED,readOnly
- PROPAGATION_REQUIRED
-
-
-
-----
-
-Note that in the example above, we have explicitly marked the parent bean definition as
-__abstract__ by using the __abstract__ attribute, as described
-<>, so that it may not actually ever be
-instantiated. Application contexts (but not simple bean factories) will by default
-pre-instantiate all singletons. It is therefore 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 try to
-pre-instantiate it.
-
-
-
-
-[[classic-aop-prog]]
-=== Creating AOP proxies programmatically with the ProxyFactory
-It's easy to create AOP proxies programmatically using Spring. This enables you to use
-Spring AOP without dependency on Spring IoC.
-
-The following listing shows creation of a proxy for a target object, with one
-interceptor and one advisor. The interfaces implemented by the target object will
-automatically be proxied:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- ProxyFactory factory = new ProxyFactory(myBusinessInterfaceImpl);
- factory.addInterceptor(myMethodInterceptor);
- factory.addAdvisor(myAdvisor);
- MyBusinessInterface tb = (MyBusinessInterface) factory.getProxy();
-----
-
-The first step is to construct an object of type
-`org.springframework.aop.framework.ProxyFactory`. You can create this with a target
-object, as in the above example, or specify the interfaces to be proxied in an alternate
-constructor.
-
-You can add interceptors or advisors, and manipulate them for the life of the
-ProxyFactory. If you add an IntroductionInterceptionAroundAdvisor you can cause the
-proxy to implement additional interfaces.
-
-There are also convenience methods on ProxyFactory (inherited from `AdvisedSupport`)
-which allow you to add other advice types such as before and throws advice.
-AdvisedSupport is the superclass of both ProxyFactory and ProxyFactoryBean.
-
-[TIP]
-====
-
-Integrating AOP proxy creation with the IoC framework is best practice in most
-applications. We recommend that you externalize configuration from Java code with AOP,
-as in general.
-====
-
-
-
-
-[[classic-aop-api-advised]]
-=== Manipulating advised objects
-However you create AOP proxies, you can manipulate them using the
-`org.springframework.aop.framework.Advised` interface. Any AOP proxy can be cast to this
-interface, whichever other interfaces it implements. This interface includes the
-following methods:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- Advisor[] getAdvisors();
-
- void addAdvice(Advice advice) throws AopConfigException;
-
- void addAdvice(int pos, Advice advice) throws AopConfigException;
-
- void addAdvisor(Advisor advisor) throws AopConfigException;
-
- void addAdvisor(int pos, Advisor advisor) throws AopConfigException;
-
- int indexOf(Advisor advisor);
-
- boolean removeAdvisor(Advisor advisor) throws AopConfigException;
-
- void removeAdvisor(int index) throws AopConfigException;
-
- boolean replaceAdvisor(Advisor a, Advisor b) throws AopConfigException;
-
- boolean isFrozen();
-----
-
-The `getAdvisors()` method will return an Advisor for every advisor, interceptor or
-other advice type that has been added to the factory. If you added an Advisor, the
-returned advisor at this index will be the object that you added. If you added an
-interceptor or other advice type, Spring will have wrapped this in an advisor with a
-pointcut that always returns true. Thus if you added a `MethodInterceptor`, the advisor
-returned for this index will be an `DefaultPointcutAdvisor` returning your
-`MethodInterceptor` and a pointcut that matches all classes and methods.
-
-The `addAdvisor()` methods can be used to add any Advisor. Usually the advisor holding
-pointcut and advice will be the generic `DefaultPointcutAdvisor`, which can be used with
-any advice or pointcut (but not for introductions).
-
-By default, it's possible to add or remove advisors or interceptors even once a proxy
-has been created. The only restriction is that it's impossible to add or remove an
-introduction advisor, as existing proxies from the factory will not show the interface
-change. (You can obtain a new proxy from the factory to avoid this problem.)
-
-A simple example of casting an AOP proxy to the `Advised` interface and examining and
-manipulating its advice:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- Advised advised = (Advised) myObject;
- Advisor[] advisors = advised.getAdvisors();
- int oldAdvisorCount = advisors.length;
- System.out.println(oldAdvisorCount + " advisors");
-
- // Add an advice like an interceptor without a pointcut
- // Will match all proxied methods
- // Can use for interceptors, before, after returning or throws advice
- advised.addAdvice(new DebugInterceptor());
-
- // Add selective advice using a pointcut
- advised.addAdvisor(new DefaultPointcutAdvisor(mySpecialPointcut, myAdvice));
-
- assertEquals("Added two advisors", oldAdvisorCount + 2, advised.getAdvisors().length);
-----
-
-[NOTE]
-====
-It's questionable whether it's advisable (no pun intended) to modify advice on a
-business object in production, although there are no doubt legitimate usage cases.
-However, it can be very useful in development: for example, in tests. I have sometimes
-found it very useful to be able to add test code in the form of an interceptor or other
-advice, getting inside a method invocation I want to test. (For example, the advice can
-get inside a transaction created for that method: for example, to run SQL to check that
-a database was correctly updated, before marking the transaction for roll back.)
-====
-
-Depending on how you created the proxy, you can usually set a `frozen` flag, in which
-case the `Advised` `isFrozen()` method will return true, and any attempts to modify
-advice through addition or removal will result in an `AopConfigException`. The ability
-to freeze the state of an advised object is useful in some cases, for example, to
-prevent calling code removing a security interceptor. It may also be used in Spring 1.1
-to allow aggressive optimization if runtime advice modification is known not to be
-required.
-
-
-
-
-[[classic-aop-autoproxy]]
-=== Using the "autoproxy" facility
-So far we've considered explicit creation of AOP proxies using a `ProxyFactoryBean` or
-similar factory bean.
-
-Spring also allows us to use "autoproxy" bean definitions, which can automatically proxy
-selected bean definitions. This is built on Spring "bean post processor" infrastructure,
-which enables modification of any bean definition as the container loads.
-
-In this model, you set up some special bean definitions in your XML bean definition file
-to configure the auto proxy infrastructure. This allows you just to declare the targets
-eligible for autoproxying: you don't need to use `ProxyFactoryBean`.
-
-There are two ways to do this:
-
-* Using an autoproxy creator that refers to specific beans in the current context.
-* A special case of autoproxy creation that deserves to be considered separately;
- autoproxy creation driven by source-level metadata attributes.
-
-
-
-[[classic-aop-autoproxy-choices]]
-==== Autoproxy bean definitions
-The `org.springframework.aop.framework.autoproxy` package provides the following
-standard autoproxy creators.
-
-
-[[classic-aop-api-autoproxy]]
-===== BeanNameAutoProxyCreator
-The `BeanNameAutoProxyCreator` class is a `BeanPostProcessor` that automatically creates
-AOP proxies for beans with names matching literal values or wildcards.
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
- jdk*,onlyJdk
-
-
- myInterceptor
-
-
-
-----
-
-As with `ProxyFactoryBean`, there is an `interceptorNames` property rather than a list
-of interceptors, to allow correct behavior for prototype advisors. Named "interceptors"
-can be advisors or any advice type.
-
-As with auto proxying in general, the main point of using `BeanNameAutoProxyCreator` is
-to apply the same configuration consistently to multiple objects, with minimal volume of
-configuration. It is a popular choice for applying declarative transactions to multiple
-objects.
-
-Bean definitions whose names match, such as "jdkMyBean" and "onlyJdk" in the above
-example, are plain old bean definitions with the target class. An AOP proxy will be
-created automatically by the `BeanNameAutoProxyCreator`. The same advice will be applied
-to all matching beans. Note that if advisors are used (rather than the interceptor in
-the above example), the pointcuts may apply differently to different beans.
-
-
-[[classic-aop-api-autoproxy-default]]
-===== DefaultAdvisorAutoProxyCreator
-A more general and extremely powerful auto proxy creator is
-`DefaultAdvisorAutoProxyCreator`. This will automagically apply eligible advisors in the
-current context, without the need to include specific bean names in the autoproxy
-advisor's bean definition. It offers the same merit of consistent configuration and
-avoidance of duplication as `BeanNameAutoProxyCreator`.
-
-Using this mechanism involves:
-
-* Specifying a `DefaultAdvisorAutoProxyCreator` bean definition.
-* Specifying any number of Advisors in the same or related contexts. Note that these
- __must__ be Advisors, not just interceptors or other advices. This is necessary
- because there must be a pointcut to evaluate, to check the eligibility of each advice
- to candidate bean definitions.
-
-The `DefaultAdvisorAutoProxyCreator` will automatically evaluate the pointcut contained
-in each advisor, to see what (if any) advice it should apply to each business object
-(such as "businessObject1" and "businessObject2" in the example).
-
-This means that any number of advisors can be applied automatically to each business
-object. If no pointcut in any of the advisors matches any method in a business object,
-the object will not be proxied. As bean definitions are added for new business objects,
-they will automatically be proxied if necessary.
-
-Autoproxying in general has the advantage of making it impossible for callers or
-dependencies to obtain an un-advised object. Calling getBean("businessObject1") on this
-ApplicationContext will return an AOP proxy, not the target business object. (The "inner
-bean" idiom shown earlier also offers this benefit.)
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-
-
-
-
-
-
-
-----
-
-The `DefaultAdvisorAutoProxyCreator` is very useful if you want to apply the same advice
-consistently to many business objects. Once the infrastructure definitions are in place,
-you can simply add new business objects without including specific proxy configuration.
-You can also drop in additional aspects very easily - for example, tracing or
-performance monitoring aspects - with minimal change to configuration.
-
-The DefaultAdvisorAutoProxyCreator offers support for filtering (using a naming
-convention so that only certain advisors are evaluated, allowing use of multiple,
-differently configured, AdvisorAutoProxyCreators in the same factory) and ordering.
-Advisors can implement the `org.springframework.core.Ordered` interface to ensure
-correct ordering if this is an issue. The TransactionAttributeSourceAdvisor used in the
-above example has a configurable order value; the default setting is unordered.
-
-
-[[classic-aop-api-autoproxy-abstract]]
-===== AbstractAdvisorAutoProxyCreator
-This is the superclass of DefaultAdvisorAutoProxyCreator. You can create your own
-autoproxy creators by subclassing this class, in the unlikely event that advisor
-definitions offer insufficient customization to the behavior of the framework
-`DefaultAdvisorAutoProxyCreator`.
-
-
-
-[[classic-aop-autoproxy-metadata]]
-==== Using metadata-driven auto-proxying
-A particularly important type of autoproxying is driven by metadata. This produces a
-similar programming model to .NET `ServicedComponents`. Instead of using XML deployment
-descriptors as in EJB, configuration for transaction management and other enterprise
-services is held in source-level attributes.
-
-In this case, you use the `DefaultAdvisorAutoProxyCreator`, in combination with Advisors
-that understand metadata attributes. The metadata specifics are held in the pointcut
-part of the candidate advisors, rather than in the autoproxy creation class itself.
-
-This is really a special case of the `DefaultAdvisorAutoProxyCreator`, but deserves
-consideration on its own. (The metadata-aware code is in the pointcuts contained in the
-advisors, not the AOP framework itself.)
-
-The `/attributes` directory of the JPetStore sample application shows the use of
-attribute-driven autoproxying. In this case, there's no need to use the
-`TransactionProxyFactoryBean`. Simply defining transactional attributes on business
-objects is sufficient, because of the use of metadata-aware pointcuts. The bean
-definitions include the following code, in `/WEB-INF/declarativeServices.xml`. Note that
-this is generic, and can be used outside the JPetStore:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-----
-
-The `DefaultAdvisorAutoProxyCreator` bean definition (the name is not significant, hence
-it can even be omitted) will pick up all eligible pointcuts in the current application
-context. In this case, the "transactionAdvisor" bean definition, of type
-`TransactionAttributeSourceAdvisor`, will apply to classes or methods carrying a
-transaction attribute. The TransactionAttributeSourceAdvisor depends on a
-TransactionInterceptor, via constructor dependency. The example resolves this via
-autowiring. The `AttributesTransactionAttributeSource` depends on an implementation of
-the `org.springframework.metadata.Attributes` interface. In this fragment, the
-"attributes" bean satisfies this, using the Jakarta Commons Attributes API to obtain
-attribute information. (The application code must have been compiled using the Commons
-Attributes compilation task.)
-
-The `/annotation` directory of the JPetStore sample application contains an analogous
-example for auto-proxying driven by JDK 1.5+ annotations. The following configuration
-enables automatic detection of Spring's `Transactional` annotation, leading to implicit
-proxies for beans containing that annotation:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-
-
-
-
-
-
-----
-
-The `TransactionInterceptor` defined here depends on a `PlatformTransactionManager`
-definition, which is not included in this generic file (although it could be) because it
-will be specific to the application's transaction requirements (typically JTA, as in
-this example, or Hibernate, JDO or JDBC):
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-----
-
-[TIP]
-====
-
-If you require only declarative transaction management, using these generic XML
-definitions will result in Spring automatically proxying all classes or methods with
-transaction attributes. You won't need to work directly with AOP, and the programming
-model is similar to that of .NET ServicedComponents.
-====
-
-This mechanism is extensible. It's possible to do autoproxying based on custom
-attributes. You need to:
-
-* Define your custom attribute.
-* Specify an Advisor with the necessary advice, including a pointcut that is triggered
- by the presence of the custom attribute on a class or method. You may be able to use
- an existing advice, merely implementing a static pointcut that picks up the custom
- attribute.
-
-It's possible for such advisors to be unique to each advised class (for example,
-mixins): they simply need to be defined as prototype, rather than singleton, bean
-definitions. For example, the `LockMixin` introduction interceptor from the Spring test
-suite, shown above, could be used in conjunction with an attribute-driven pointcut to
-target a mixin, as shown here. We use the generic `DefaultPointcutAdvisor`, configured
-using JavaBean properties:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-----
-
-The above `swap()` call changes the target of the swappable bean. Clients who hold a
-reference to that bean will be unaware of the change, but will immediately start hitting
-the new target.
-
-Although this example doesn't add any advice - and it's not necessary to add advice to
-use a `TargetSource` - of course any `TargetSource` can be used in conjunction with
-arbitrary advice.
-
-
-
-[[classic-aop-ts-pool]]
-==== Pooling target sources
-Using a pooling target source provides a similar programming model to stateless session
-EJBs, in which a pool of identical instances is maintained, with method invocations
-going to free objects in the pool.
-
-A crucial difference between Spring pooling and SLSB pooling is that Spring pooling can
-be applied to any POJO. As with Spring in general, this service can be applied in a
-non-invasive way.
-
-Spring provides out-of-the-box support for Jakarta Commons Pool 1.3, which provides a
-fairly efficient pooling implementation. You'll need the commons-pool Jar on your
-application's classpath to use this feature. It's also possible to subclass
-`org.springframework.aop.target.AbstractPoolingTargetSource` to support any other
-pooling API.
-
-Sample configuration is shown below:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
- ... properties omitted
-
-
-
-
-
-
-
-
-
-
-
-----
-
-Note that the target object - "businessObjectTarget" in the example - __must__ be a
-prototype. This allows the `PoolingTargetSource` implementation to create new instances
-of the target to grow the pool as necessary. See the Javadoc for
-`AbstractPoolingTargetSource` and the concrete subclass you wish to use for information
-about its properties: "maxSize" is the most basic, and always guaranteed to be present.
-
-In this case, "myInterceptor" is the name of an interceptor that would need to be
-defined in the same IoC context. However, it isn't necessary to specify interceptors to
-use pooling. If you want only pooling, and no other advice, don't set the
-interceptorNames property at all.
-
-It's possible to configure Spring so as to be able to cast any pooled object to the
-`org.springframework.aop.target.PoolingConfig` interface, which exposes information
-about the configuration and current size of the pool through an introduction. You'll
-need to define an advisor like this:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-----
-
-This advisor is obtained by calling a convenience method on the
-`AbstractPoolingTargetSource` class, hence the use of MethodInvokingFactoryBean. This
-advisor's name ("poolConfigAdvisor" here) must be in the list of interceptors names in
-the ProxyFactoryBean exposing the pooled object.
-
-The cast will look as follows:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- PoolingConfig conf = (PoolingConfig) beanFactory.getBean("businessObject");
- System.out.println("Max pool size is " + conf.getMaxSize());
-----
-
-[NOTE]
-====
-Pooling stateless service objects is not usually necessary. We don't believe it should
-be the default choice, as most stateless objects are naturally thread safe, and instance
-pooling is problematic if resources are cached.
-====
-
-Simpler pooling is available using autoproxying. It's possible to set the TargetSources
-used by any autoproxy creator.
-
-
-
-[[classic-aop-ts-prototype]]
-==== Prototype target sources
-Setting up a "prototype" target source is similar to a pooling TargetSource. In this
-case, a new instance of the target will be created on every method invocation. Although
-the cost of creating a new object isn't high in a modern JVM, the cost of wiring up the
-new object (satisfying its IoC dependencies) may be more expensive. Thus you shouldn't
-use this approach without very good reason.
-
-To do this, you could modify the `poolTargetSource` definition shown above as follows.
-(I've also changed the name, for clarity.)
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-----
-
-There's only one property: the name of the target bean. Inheritance is used in the
-TargetSource implementations to ensure consistent naming. As with the pooling target
-source, the target bean must be a prototype bean definition.
-
-
-
-[[classic-aop-ts-threadlocal]]
-==== ThreadLocal target sources
-
-`ThreadLocal` target sources are useful if you need an object to be created for each
-incoming request (per thread that is). The concept of a `ThreadLocal` provide a JDK-wide
-facility to transparently store resource alongside a thread. Setting up a
-`ThreadLocalTargetSource` is pretty much the same as was explained for the other types
-of target source:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-----
-
-[NOTE]
-====
-ThreadLocals come with serious issues (potentially resulting in memory leaks) when
-incorrectly using them in a multi-threaded and multi-classloader environments. One
-should always consider wrapping a threadlocal in some other class and never directly use
-the `ThreadLocal` itself (except of course in the wrapper class). Also, one should
-always remember to correctly set and unset (where the latter simply involved a call to
-`ThreadLocal.set(null)`) the resource local to the thread. Unsetting should be done in
-any case since not unsetting it might result in problematic behavior. Spring's
-ThreadLocal support does this for you and should always be considered in favor of using
-ThreadLocals without other proper handling code.
-====
-
-
-
-
-[[classic-aop-extensibility]]
-=== Defining new Advice types
-
-Spring AOP is designed to be extensible. While the interception implementation strategy
-is presently used internally, it is possible to support arbitrary advice types in
-addition to the out-of-the-box interception around advice, before, throws advice and
-after returning advice.
-
-The `org.springframework.aop.framework.adapter` package is an SPI package allowing
-support for new custom advice types to be added without changing the core framework. The
-only constraint on a custom `Advice` type is that it must implement the
-`org.aopalliance.aop.Advice` tag interface.
-
-Please refer to the `org.springframework.aop.framework.adapter` package's Javadocs for
-further information.
-
-
-
-
-[[classic-aop-api-resources]]
-=== Further resources
-Please refer to the Spring sample applications for further examples of Spring AOP:
-
-* The JPetStore's default configuration illustrates the use of the
- `TransactionProxyFactoryBean` for declarative transaction management.
-* The `/attributes` directory of the JPetStore illustrates the use of attribute-driven
- declarative transaction management.
-
-
-[[xsd-config]]
-== XML Schema-based configuration
-
-
-[[xsd-config-introduction]]
-=== Introduction
-This appendix details the XML Schema-based configuration introduced in Spring 2.0 and
-enhanced and extended in Spring 2.5 and 3.0.
-
-.DTD support?
-****
-Authoring Spring configuration files using the older DTD style is still fully supported.
-
-Nothing will break if you forego the use of the new XML Schema-based approach to
-authoring Spring XML configuration files. All that you lose out on is the opportunity to
-have more succinct and clearer configuration. Regardless of whether the XML
-configuration is DTD- or Schema-based, in the end it all boils down to the same object
-model in the container (namely one or more `BeanDefinition` instances).
-****
-
-The central motivation for moving to XML Schema based configuration files was to make
-Spring XML configuration easier. The __'classic'__ ``-based approach is good, but
-its generic-nature comes with a price in terms of configuration overhead.
-
-From the Spring IoC containers point-of-view, __everything__ is a bean. That's great
-news for the Spring IoC container, because if everything is a bean then everything can
-be treated in the exact same fashion. The same, however, is not true from a developer's
-point-of-view. The objects defined in a Spring XML configuration file are not all
-generic, vanilla beans. Usually, each bean requires some degree of specific
-configuration.
-
-Spring 2.0's new XML Schema-based configuration addresses this issue. The ``
-element is still present, and if you wanted to, you could continue to write the __exact
-same__ style of Spring XML configuration using only `` elements. The new XML
-Schema-based configuration does, however, make Spring XML configuration files
-substantially clearer to read. In addition, it allows you to express the intent of a
-bean definition.
-
-The key thing to remember is that the new custom tags work best for infrastructure or
-integration beans: for example, AOP, collections, transactions, integration with
-3rd-party frameworks such as Mule, etc., while the existing bean tags are best suited to
-application-specific beans, such as DAOs, service layer objects, validators, etc.
-
-The examples included below will hopefully convince you that the inclusion of XML Schema
-support in Spring 2.0 was a good idea. The reception in the community has been
-encouraging; also, please note the fact that this new configuration mechanism is totally
-customisable and extensible. This means you can write your own domain-specific
-configuration tags that would better represent your application's domain; the process
-involved in doing so is covered in the appendix entitled <>.
-
-
-
-
-[[xsd-config-body]]
-=== XML Schema-based configuration
-
-
-
-[[xsd-config-body-referencing]]
-==== Referencing the schemas
-To switch over from the DTD-style to the new XML Schema-style, you need to make the
-following change.
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-
-
-----
-
-The equivalent file in the XML Schema-style would be...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-----
-
-[NOTE]
-====
-The `'xsi:schemaLocation'` fragment is not actually required, but can be included to
-reference a local copy of a schema (which can be useful during development).
-====
-
-The above Spring XML configuration fragment is boilerplate that you can copy and paste
-(!) and then plug `` definitions into like you have always done. However, the
-entire point of switching over is to take advantage of the new Spring 2.0 XML tags since
-they make configuration easier. The section entitled <>
-demonstrates how you can start immediately by using some of the more common utility tags.
-
-The rest of this chapter is devoted to showing examples of the new Spring XML Schema
-based configuration, with at least one example for every new tag. The format follows a
-before and after style, with a __before__ snippet of XML showing the old (but still 100%
-legal and supported) style, followed immediately by an __after__ example showing the
-equivalent in the new XML Schema-based style.
-
-
-
-[[xsd-config-body-schemas-util]]
-==== the util schema
-
-First up is coverage of the `util` tags. As the name implies, the `util` tags deal with
-common, __utility__ configuration issues, such as configuring collections, referencing
-constants, and suchlike.
-
-To use the tags in the `util` schema, you need to have the following preamble at the top
-of your Spring XML configuration file; the text in the snippet below references the
-correct schema so that the tags in the `util` namespace are available to you.
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-----
-
-
-[[xsd-config-body-schemas-util-constant]]
-=====
-
-Before...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-----
-
-The above configuration uses a Spring `FactoryBean` implementation, the
-`FieldRetrievingFactoryBean`, to set the value of the `'isolation'` property on a bean
-to the value of the `'java.sql.Connection.TRANSACTION_SERIALIZABLE'` constant. This is
-all well and good, but it is a tad verbose and (unnecessarily) exposes Spring's internal
-plumbing to the end user.
-
-The following XML Schema-based version is more concise and clearly expresses the
-developer's intent (__'inject this constant value'__), and it just reads better.
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-----
-
-[[xsd-config-body-schemas-util-frfb]]
-====== Setting a bean property or constructor arg from a field value
-http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/config/FieldRetrievingFactoryBean.html[`FieldRetrievingFactoryBean`]
-is a `FactoryBean` which retrieves a `static` or non-static field value. It is typically
-used for retrieving `public` `static` `final` constants, which may then be used to set a
-property value or constructor arg for another bean.
-
-Find below an example which shows how a `static` field is exposed, by using the
-http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/config/FieldRetrievingFactoryBean.html#setStaticField(java.lang.String)[`staticField`]
-property:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-----
-
-There is also a convenience usage form where the `static` field is specified as the bean
-name:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-----
-
-This does mean that there is no longer any choice in what the bean id is (so any other
-bean that refers to it will also have to use this longer name), but this form is very
-concise to define, and very convenient to use as an inner bean since the id doesn't have
-to be specified for the bean reference:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-----
-
-It is also possible to access a non-static (instance) field of another bean, as
-described in the API documentation for the
-http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/beans/factory/config/FieldRetrievingFactoryBean.html[`FieldRetrievingFactoryBean`]
-class.
-
-Injecting enum values into beans as either property or constructor arguments is very
-easy to do in Spring, in that you don't actually have to __do__ anything or know
-anything about the Spring internals (or even about classes such as the
-`FieldRetrievingFactoryBean`). Let's look at an example to see how easy injecting an
-enum value is; consider this JDK 5 enum:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- package javax.persistence;
-
- public enum PersistenceContextType {
-
- TRANSACTION,
- EXTENDED
-
- }
-----
-
-Now consider a setter of type `PersistenceContextType`:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- package example;
-
- public class Client {
-
- private PersistenceContextType persistenceContextType;
-
- public void setPersistenceContextType(PersistenceContextType type) {
- this.persistenceContextType = type;
- }
-
- }
-----
-
-.. and the corresponding bean definition:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-----
-
-This works for classic type-safe emulated enums (on JDK 1.4 and JDK 1.3) as well; Spring
-will automatically attempt to match the string property value to a constant on the enum
-class.
-
-
-[[xsd-config-body-schemas-util-property-path]]
-=====
-
-Before...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-
-
-
-
-
-
-----
-
-The above configuration uses a Spring `FactoryBean` implementation, the
-`PropertyPathFactoryBean`, to create a bean (of type `int`) called `'testBean.age'` that
-has a value equal to the `'age'` property of the `'testBean'` bean.
-
-After...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-
-
-
-
-
-
-----
-
-The value of the `'path'` attribute of the `` tag follows the form
-`'beanName.beanProperty'`.
-
-[[xsd-config-body-schemas-util-property-path-dependency]]
-====== Using to set a bean property or constructor-argument
-
-`PropertyPathFactoryBean` is a `FactoryBean` that evaluates a property path on a given
-target object. The target object can be specified directly or via a bean name. This
-value may then be used in another bean definition as a property value or constructor
-argument.
-
-Here's an example where a path is used against another bean, by name:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
- // target bean to be referenced by name
-
-
-
-
-
-
-
-
-
- // will result in 11, which is the value of property 'spouse.age' of bean 'person'
-
-
-
-
-----
-
-In this example, a path is evaluated against an inner bean:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-
-
-
-----
-
-There is also a shortcut form, where the bean name is the property path.
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-----
-
-This form does mean that there is no choice in the name of the bean. Any reference to it
-will also have to use the same id, which is the path. Of course, if used as an inner
-bean, there is no need to refer to it at all:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-----
-
-The result type may be specifically set in the actual definition. This is not necessary
-for most use cases, but can be of use for some. Please see the Javadocs for more info on
-this feature.
-
-
-[[xsd-config-body-schemas-util-properties]]
-=====
-
-Before...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-----
-
-The above configuration uses a Spring `FactoryBean` implementation, the
-`PropertiesFactoryBean`, to instantiate a `java.util.Properties` instance with values
-loaded from the supplied <> location).
-
-After...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-----
-
-
-[[xsd-config-body-schemas-util-list]]
-=====
-
-Before...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
- pechorin@hero.org
- raskolnikov@slums.org
- stavrogin@gov.org
- porfiry@gov.org
-
-
-
-----
-
-The above configuration uses a Spring `FactoryBean` implementation, the
-`ListFactoryBean`, to create a `java.util.List` instance initialized with values taken
-from the supplied `'sourceList'`.
-
-After...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
- pechorin@hero.org
- raskolnikov@slums.org
- stavrogin@gov.org
- porfiry@gov.org
-
-----
-
-You can also explicitly control the exact type of `List` that will be instantiated and
-populated via the use of the `'list-class'` attribute on the `` element. For
-example, if we really need a `java.util.LinkedList` to be instantiated, we could use the
-following configuration:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
- jackshaftoe@vagabond.org
- eliza@thinkingmanscrumpet.org
- vanhoek@pirate.org
- d'Arcachon@nemesis.org
-
-----
-
-If no `'list-class'` attribute is supplied, a `List` implementation will be chosen by
-the container.
-
-
-[[xsd-config-body-schemas-util-map]]
-=====
-
-Before...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-----
-
-The above configuration uses a Spring `FactoryBean` implementation, the
-`MapFactoryBean`, to create a `java.util.Map` instance initialized with key-value pairs
-taken from the supplied `'sourceMap'`.
-
-After...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-
-----
-
-You can also explicitly control the exact type of `Map` that will be instantiated and
-populated via the use of the `'map-class'` attribute on the `` element. For
-example, if we really need a `java.util.TreeMap` to be instantiated, we could use the
-following configuration:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-----
-
-If no `'map-class'` attribute is supplied, a `Map` implementation will be chosen by the
-container.
-
-
-[[xsd-config-body-schemas-util-set]]
-=====
-
-Before...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
- pechorin@hero.org
- raskolnikov@slums.org
- stavrogin@gov.org
- porfiry@gov.org
-
-
-
-----
-
-The above configuration uses a Spring `FactoryBean` implementation, the
-`SetFactoryBean`, to create a `java.util.Set` instance initialized with values taken
-from the supplied `'sourceSet'`.
-
-After...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
- pechorin@hero.org
- raskolnikov@slums.org
- stavrogin@gov.org
- porfiry@gov.org
-
-----
-
-You can also explicitly control the exact type of `Set` that will be instantiated and
-populated via the use of the `'set-class'` attribute on the `` element. For
-example, if we really need a `java.util.TreeSet` to be instantiated, we could use the
-following configuration:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
- pechorin@hero.org
- raskolnikov@slums.org
- stavrogin@gov.org
- porfiry@gov.org
-
-----
-
-If no `'set-class'` attribute is supplied, a `Set` implementation will be chosen by the
-container.
-
-
-
-[[xsd-config-body-schemas-jee]]
-==== the jee schema
-
-The `jee` tags deal with Java EE (Java Enterprise Edition)-related configuration issues,
-such as looking up a JNDI object and defining EJB references.
-
-To use the tags in the `jee` schema, you need to have the following preamble at the top
-of your Spring XML configuration file; the text in the following snippet references the
-correct schema so that the tags in the `jee` namespace are available to you.
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-----
-
-
-[[xsd-config-body-schemas-jee-jndi-lookup]]
-===== (simple)
-
-Before...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-
-----
-
-After...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-----
-
-
-[[xsd-config-body-schemas-jee-jndi-lookup-environment-single]]
-===== (with single JNDI environment setting)
-
-Before...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
- bar
-
-
-
-----
-
-After...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
- foo=bar
-
-----
-
-
-[[xsd-config-body-schemas-jee-jndi-lookup-evironment-multiple]]
-===== (with multiple JNDI environment settings)
-
-Before...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
- bar
- pong
-
-
-
-----
-
-After...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
- foo=bar
- ping=pong
-
-
-----
-
-
-[[xsd-config-body-schemas-jee-jndi-lookup-complex]]
-===== (complex)
-
-Before...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-
-
-----
-
-After...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-----
-
-
-[[xsd-config-body-schemas-jee-local-slsb]]
-===== (simple)
-
-The `` tag configures a reference to an EJB Stateless SessionBean.
-
-Before...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-----
-
-After...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-----
-
-
-[[xsd-config-body-schemas-jee-local-slsb-complex]]
-===== (complex)
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-
-----
-
-After...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-----
-
-
-[[xsd-config-body-schemas-jee-remote-slsb]]
-=====
-
-The `` tag configures a reference to a `remote` EJB Stateless
-SessionBean.
-
-Before...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-
-
-
-----
-
-After...
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-----
-
-
-
-[[xsd-config-body-schemas-lang]]
-==== the lang schema
-
-The `lang` tags deal with exposing objects that have been written in a dynamic language
-such as JRuby or Groovy as beans in the Spring container.
-
-These tags (and the dynamic language support) are comprehensively covered in the chapter
-entitled <>. Please do consult that chapter for full details on this
-support and the `lang` tags themselves.
-
-In the interest of completeness, to use the tags in the `lang` schema, you need to have
-the following preamble at the top of your Spring XML configuration file; the text in the
-following snippet references the correct schema so that the tags in the `lang` namespace
-are available to you.
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-----
-
-
-
-[[xsd-config-body-schemas-jms]]
-==== the jms schema
-
-The `jms` tags deal with configuring JMS-related beans such as Spring's
-<>. These tags are detailed in the section of the
-<> entitled <>. Please do consult that chapter for full
-details on this support and the `jms` tags themselves.
-
-In the interest of completeness, to use the tags in the `jms` schema, you need to have
-the following preamble at the top of your Spring XML configuration file; the text in the
-following snippet references the correct schema so that the tags in the `jms` namespace
-are available to you.
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-----
-
-
-
-[[xsd-config-body-schemas-tx]]
-==== the tx (transaction) schema
-
-The `tx` tags deal with configuring all of those beans in Spring's comprehensive support
-for transactions. These tags are covered in the chapter entitled <>.
-
-[TIP]
-====
-
-You are strongly encouraged to look at the `'spring-tx.xsd'` file that ships with the
-Spring distribution. This file is (of course), the XML Schema for Spring's transaction
-configuration, and covers all of the various tags in the `tx` namespace, including
-attribute defaults and suchlike. This file is documented inline, and thus the
-information is not repeated here in the interests of adhering to the DRY (Don't Repeat
-Yourself) principle.
-====
-
-In the interest of completeness, to use the tags in the `tx` schema, you need to have
-the following preamble at the top of your Spring XML configuration file; the text in the
-following snippet references the correct schema so that the tags in the `tx` namespace
-are available to you.
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-----
-
-[NOTE]
-====
-Often when using the tags in the `tx` namespace you will also be using the tags from the
-`aop` namespace (since the declarative transaction support in Spring is implemented
-using AOP). The above XML snippet contains the relevant lines needed to reference the
-`aop` schema so that the tags in the `aop` namespace are available to you.
-====
-
-
-
-[[xsd-config-body-schemas-aop]]
-==== the aop schema
-
-The `aop` tags deal with configuring all things AOP in Spring: this includes Spring's
-own proxy-based AOP framework and Spring's integration with the AspectJ AOP framework.
-These tags are comprehensively covered in the chapter entitled <>.
-
-In the interest of completeness, to use the tags in the `aop` schema, you need to have
-the following preamble at the top of your Spring XML configuration file; the text in the
-following snippet references the correct schema so that the tags in the `aop` namespace
-are available to you.
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-----
-
-
-
-[[xsd-config-body-schemas-context]]
-==== the context schema
-
-The `context` tags deal with `ApplicationContext` configuration that relates to plumbing
-- that is, not usually beans that are important to an end-user but rather beans that do
-a lot of grunt work in Spring, such as `BeanfactoryPostProcessors`. The following
-snippet references the correct schema so that the tags in the `context` namespace are
-available to you.
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-----
-
-[NOTE]
-====
-The `context` schema was only introduced in Spring 2.5.
-====
-
-
-[[xsd-config-body-schemas-context-pphc]]
-=====
-
-This element activates the replacement of `${...}` placeholders, resolved against the
-specified properties file (as a <>). This element is
-a convenience mechanism that sets up a<> for you; if you need more control over the
-`PropertyPlaceholderConfigurer`, just define one yourself explicitly.
-
-
-[[xsd-config-body-schemas-context-ac]]
-=====
-
-Activates the Spring infrastructure for various annotations to be detected in bean
-classes: Spring's <> and
-<>, as well as JSR 250's `@PostConstruct`,
-`@PreDestroy` and `@Resource` (if available), and JPA's `@PersistenceContext` and
-`@PersistenceUnit` (if available). Alternatively, you can choose to activate the
-individual `BeanPostProcessors` for those annotations explicitly.
-
-[NOTE]
-====
-This element does __not__ activate processing of Spring's
-<> annotation. Use the
-<`>> element for that purpose.
-====
-
-
-[[xsd-config-body-schemas-context-component-scan]]
-=====
-
-This element is detailed in <>.
-
-
-[[xsd-config-body-schemas-context-ltw]]
-=====
-
-This element is detailed in <>.
-
-
-[[xsd-config-body-schemas-context-sc]]
-=====
-
-This element is detailed in <>.
-
-
-[[xsd-config-body-schemas-context-mbe]]
-=====
-
-This element is detailed in <>.
-
-
-
-[[xsd-config-body-schemas-tool]]
-==== the tool schema
-
-The `tool` tags are for use when you want to add tooling-specific metadata to your
-custom configuration elements. This metadata can then be consumed by tools that are
-aware of this metadata, and the tools can then do pretty much whatever they want with it
-(validation, etc.).
-
-The `tool` tags are not documented in this release of Spring as they are currently
-undergoing review. If you are a third party tool vendor and you would like to contribute
-to this review process, then do mail the Spring mailing list. The currently supported
-`tool` tags can be found in the file `'spring-tool.xsd'` in the
-`'src/org/springframework/beans/factory/xml'` directory of the Spring source
-distribution.
-
-
-
-[[xsd-config-body-schemas-jdbc]]
-==== the jdbc schema
-
-The `jdbc` tags allow you to quickly configure an embedded database or initialize an
-existing data source. These tags are documented in <>
-and <> respectively.
-
-To use the tags in the `jdbc` schema, you need to have the following preamble at the top
-of your Spring XML configuration file; the text in the following snippet references the
-correct schema so that the tags in the `jdbc` namespace are available to you.
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-----
-
-
-
-[[xsd-config-body-schemas-cache]]
-==== the cache schema
-
-The `cache` tags can be used to enable support for Spring's `@CacheEvict`, `@CachePut`
-and `@Caching` annotations. It it also supports declarative XML-based caching. See
-<> and <> for details.
-
-To use the tags in the `cache` schema, you need to have the following preamble at the
-top of your Spring XML configuration file; the text in the following snippet references
-the correct schema so that the tags in the `cache` namespace are available to you.
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-----
-
-
-
-[[xsd-config-body-schemas-beans]]
-==== the beans schema
-
-Last but not least we have the tags in the `beans` schema. These are the same tags that
-have been in Spring since the very dawn of the framework. Examples of the various tags
-in the `beans` schema are not shown here because they are quite comprehensively covered
-in <> (and indeed in that entire <>).
-
-One thing that is new to the beans tags themselves in Spring 2.0 is the idea of
-arbitrary bean metadata. In Spring 2.0 it is now possible to add zero or more key /
-value pairs to `` XML definitions. What, if anything, is done with this extra
-metadata is totally up to your own custom logic (and so is typically only of use if you
-are writing your own custom tags as described in the appendix entitled
-<>).
-
-Find below an example of the `` tag in the context of a surrounding ``
-(please note that without any logic to interpret it the metadata is effectively useless
-as-is).
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
- ____
-
-
-
-
-----
-
-In the case of the above example, you would assume that there is some logic that will
-consume the bean definition and set up some caching infrastructure using the supplied
-metadata.
-
-
-
-
-
-[[extensible-xml]]
-== Extensible XML authoring
-
-
-
-
-[[extensible-xml-introduction]]
-=== Introduction
-Since version 2.0, Spring has featured a mechanism for schema-based extensions to the
-basic Spring XML format for defining and configuring beans. This section is devoted to
-detailing how you would go about writing your own custom XML bean definition parsers and
-integrating such parsers into the Spring IoC container.
-
-To facilitate the authoring of configuration files using a schema-aware XML editor,
-Spring's extensible XML configuration mechanism is based on XML Schema. If you are not
-familiar with Spring's current XML configuration extensions that come with the standard
-Spring distribution, please first read the appendix entitled<>.
-
-Creating new XML configuration extensions can be done by following these (relatively)
-simple steps:
-
-* <> an XML schema to describe your custom element(s).
-* <> a custom `NamespaceHandler` implementation
- (this is an easy step, don't worry).
-* <> one or more `BeanDefinitionParser` implementations
- (this is where the real work is done).
-* <> the above artifacts with Spring (this too
- is an easy step).
-
-What follows is a description of each of these steps. For the example, we will create an
-XML extension (a custom XML element) that allows us to configure objects of the type
-`SimpleDateFormat` (from the `java.text` package) in an easy manner. When we are done,
-we will be able to define bean definitions of type `SimpleDateFormat` like this:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-----
-
-__(Don't worry about the fact that this example is very simple; much more detailed
-examples follow afterwards. The intent in this first simple example is to walk you
-through the basic steps involved.)__
-
-
-
-
-[[extensible-xml-schema]]
-=== Authoring the schema
-Creating an XML configuration extension for use with Spring's IoC container starts with
-authoring an XML Schema to describe the extension. What follows is the schema we'll use
-to configure `SimpleDateFormat` objects.
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-----
-
-(The emphasized line contains an extension base for all tags that will be identifiable
-(meaning they have an `id` attribute that will be used as the bean identifier in the
-container). We are able to use this attribute because we imported the Spring-provided
-`'beans'` namespace.)
-
-The above schema will be used to configure `SimpleDateFormat` objects, directly in an
-XML application context file using the `` element.
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-----
-
-Note that after we've created the infrastructure classes, the above snippet of XML will
-essentially be exactly the same as the following XML snippet. In other words, we're just
-creating a bean in the container, identified by the name `'dateFormat'` of type
-`SimpleDateFormat`, with a couple of properties set.
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-----
-
-[NOTE]
-====
-The schema-based approach to creating configuration format allows for tight integration
-with an IDE that has a schema-aware XML editor. Using a properly authored schema, you
-can use autocompletion to have a user choose between several configuration options
-defined in the enumeration.
-====
-
-
-
-
-[[extensible-xml-namespacehandler]]
-=== Coding a NamespaceHandler
-
-In addition to the schema, we need a `NamespaceHandler` that will parse all elements of
-this specific namespace Spring encounters while parsing configuration files. The
-`NamespaceHandler` should in our case take care of the parsing of the `myns:dateformat`
-element.
-
-The `NamespaceHandler` interface is pretty simple in that it features just three methods:
-
-* `init()` - allows for initialization of the `NamespaceHandler` and will be called by
- Spring before the handler is used
-* `BeanDefinition parse(Element, ParserContext)` - called when Spring encounters a
- top-level element (not nested inside a bean definition or a different namespace). This
- method can register bean definitions itself and/or return a bean definition.
-* `BeanDefinitionHolder decorate(Node, BeanDefinitionHolder, ParserContext)` - called
- when Spring encounters an attribute or nested element of a different namespace. The
- decoration of one or more bean definitions is used for example with
- the<>. We'll start by
- highlighting a simple example, without using decoration, after which we will show
- decoration in a somewhat more advanced example.
-
-Although it is perfectly possible to code your own `NamespaceHandler` for the entire
-namespace (and hence provide code that parses each and every element in the namespace),
-it is often the case that each top-level XML element in a Spring XML configuration file
-results in a single bean definition (as in our case, where a single ``
-element results in a single `SimpleDateFormat` bean definition). Spring features a
-number of convenience classes that support this scenario. In this example, we'll make
-use the `NamespaceHandlerSupport` class:
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- package org.springframework.samples.xml;
-
- import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
-
- public class MyNamespaceHandler extends NamespaceHandlerSupport {
-
- public void init() {
- **registerBeanDefinitionParser("dateformat", new SimpleDateFormatBeanDefinitionParser());**
- }
-
- }
-----
-
-The observant reader will notice that there isn't actually a whole lot of parsing logic
-in this class. Indeed... the `NamespaceHandlerSupport` class has a built in notion of
-delegation. It supports the registration of any number of `BeanDefinitionParser`
-instances, to which it will delegate to when it needs to parse an element in its
-namespace. This clean separation of concerns allows a `NamespaceHandler` to handle the
-orchestration of the parsing of __all__ of the custom elements in its namespace, while
-delegating to `BeanDefinitionParsers` to do the grunt work of the XML parsing; this
-means that each `BeanDefinitionParser` will contain just the logic for parsing a single
-custom element, as we can see in the next step
-
-
-
-
-[[extensible-xml-parser]]
-=== BeanDefinitionParser
-
-A `BeanDefinitionParser` will be used if the `NamespaceHandler` encounters an XML
-element of the type that has been mapped to the specific bean definition parser (which
-is `'dateformat'` in this case). In other words, the `BeanDefinitionParser` is
-responsible for parsing __one__ distinct top-level XML element defined in the schema. In
-the parser, we'll have access to the XML element (and thus its subelements too) so that
-we can parse our custom XML content, as can be seen in the following example:
-
-[source,java,indent=0]
-----
- package org.springframework.samples.xml;
-
- import org.springframework.beans.factory.support.BeanDefinitionBuilder;
- import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
- import org.springframework.util.StringUtils;
- import org.w3c.dom.Element;
-
- import java.text.SimpleDateFormat;
-
- public class SimpleDateFormatBeanDefinitionParser extends AbstractSingleBeanDefinitionParser { // <1>
-
- protected Class getBeanClass(Element element) {
- return SimpleDateFormat.class; // <2>
- }
-
- protected void doParse(Element element, BeanDefinitionBuilder bean) {
- // this will never be null since the schema explicitly requires that a value be supplied
- String pattern = element.getAttribute("pattern");
- bean.addConstructorArg(pattern);
-
- // this however is an optional property
- String lenient = element.getAttribute("lenient");
- if (StringUtils.hasText(lenient)) {
- bean.addPropertyValue("lenient", Boolean.valueOf(lenient));
- }
- }
-
- }
-----
-
-<1> We use the Spring-provided `AbstractSingleBeanDefinitionParser` to handle a lot of
-the basic grunt work of creating a __single__ `BeanDefinition`.
-
-<2> We supply the `AbstractSingleBeanDefinitionParser` superclass with the type that our
-single `BeanDefinition` will represent.
-
-In this simple case, this is all that we need to do. The creation of our single
-`BeanDefinition` is handled by the `AbstractSingleBeanDefinitionParser` superclass, as
-is the extraction and setting of the bean definition's unique identifier.
-
-
-
-
-[[extensible-xml-registration]]
-=== Registering the handler and the schema
-The coding is finished! All that remains to be done is to somehow make the Spring XML
-parsing infrastructure aware of our custom element; we do this by registering our custom
-`namespaceHandler` and custom XSD file in two special purpose properties files. These
-properties files are both placed in a `'META-INF'` directory in your application, and
-can, for example, be distributed alongside your binary classes in a JAR file. The Spring
-XML parsing infrastructure will automatically pick up your new extension by consuming
-these special properties files, the formats of which are detailed below.
-
-
-
-[[extensible-xml-registration-spring-handlers]]
-==== 'META-INF/spring.handlers'
-
-The properties file called `'spring.handlers'` contains a mapping of XML Schema URIs to
-namespace handler classes. So for our example, we need to write the following:
-
-[literal]
-[subs="verbatim,quotes"]
-----
-http\://www.mycompany.com/schema/myns=org.springframework.samples.xml.MyNamespaceHandler
-----
-
-__(The `':'` character is a valid delimiter in the Java properties format, and so the
-`':'` character in the URI needs to be escaped with a backslash.)__
-
-The first part (the key) of the key-value pair is the URI associated with your custom
-namespace extension, and needs to __match exactly__ the value of the `'targetNamespace'`
-attribute as specified in your custom XSD schema.
-
-
-
-[[extensible-xml-registration-spring-schemas]]
-==== 'META-INF/spring.schemas'
-
-The properties file called `'spring.schemas'` contains a mapping of XML Schema locations
-(referred to along with the schema declaration in XML files that use the schema as part
-of the `'xsi:schemaLocation'` attribute) to __classpath__ resources. This file is needed
-to prevent Spring from absolutely having to use a default `EntityResolver` that requires
-Internet access to retrieve the schema file. If you specify the mapping in this
-properties file, Spring will search for the schema on the classpath (in this case
-`'myns.xsd'` in the `'org.springframework.samples.xml'` package):
-
-[literal]
-[subs="verbatim,quotes"]
-----
-http\://www.mycompany.com/schema/myns/myns.xsd=org/springframework/samples/xml/myns.xsd
-----
-
-The upshot of this is that you are encouraged to deploy your XSD file(s) right alongside
-the `NamespaceHandler` and `BeanDefinitionParser` classes on the classpath.
-
-
-
-
-[[extensible-xml-using]]
-=== Using a custom extension in your Spring XML configuration
-Using a custom extension that you yourself have implemented is no different from using
-one of the 'custom' extensions that Spring provides straight out of the box. Find below
-an example of using the custom `` element developed in the previous steps
-in a Spring XML configuration file.
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-----
-
-
-
-
-[[extensible-xml-meat]]
-=== Meatier examples
-Find below some much meatier examples of custom XML extensions.
-
-
-
-[[extensible-xml-custom-nested]]
-==== Nesting custom tags within custom tags
-This example illustrates how you might go about writing the various artifacts required
-to satisfy a target of the following configuration:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-
-
-
-
-
-
-----
-
-The above configuration actually nests custom extensions within each other. The class
-that is actually configured by the above `` element is the `Component`
-class (shown directly below). Notice how the `Component` class does __not__ expose a
-setter method for the `'components'` property; this makes it hard (or rather impossible)
-to configure a bean definition for the `Component` class using setter injection.
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- package com.foo;
-
- import java.util.ArrayList;
- import java.util.List;
-
- public class Component {
-
- private String name;
- private List components = new ArrayList ();
-
- // mmm, there is no setter method for the 'components'
- public void addComponent(Component component) {
- this.components.add(component);
- }
-
- public List getComponents() {
- return components;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- }
-----
-
-The typical solution to this issue is to create a custom `FactoryBean` that exposes a
-setter property for the `'components'` property.
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- package com.foo;
-
- import org.springframework.beans.factory.FactoryBean;
-
- import java.util.List;
-
- public class ComponentFactoryBean implements FactoryBean {
-
- private Component parent;
- private List children;
-
- public void setParent(Component parent) {
- this.parent = parent;
- }
-
- public void setChildren(List children) {
- this.children = children;
- }
-
- public Component getObject() throws Exception {
- if (this.children != null && this.children.size() > 0) {
- for (Component child : children) {
- this.parent.addComponent(child);
- }
- }
- return this.parent;
- }
-
- public Class getObjectType() {
- return Component.class;
- }
-
- public boolean isSingleton() {
- return true;
- }
-
- }
-----
-
-This is all very well, and does work nicely, but exposes a lot of Spring plumbing to the
-end user. What we are going to do is write a custom extension that hides away all of
-this Spring plumbing. If we stick to <>, we'll start off by creating the XSD schema to define the structure of our
-custom tag.
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-----
-
-We'll then create a custom `NamespaceHandler`.
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- package com.foo;
-
- import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
-
- public class ComponentNamespaceHandler extends NamespaceHandlerSupport {
-
- public void init() {
- registerBeanDefinitionParser("component", new ComponentBeanDefinitionParser());
- }
-
- }
-----
-
-Next up is the custom `BeanDefinitionParser`. Remember that what we are creating is a
-`BeanDefinition` describing a `ComponentFactoryBean`.
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- package com.foo;
-
- import org.springframework.beans.factory.config.BeanDefinition;
- import org.springframework.beans.factory.support.AbstractBeanDefinition;
- import org.springframework.beans.factory.support.BeanDefinitionBuilder;
- import org.springframework.beans.factory.support.ManagedList;
- import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser;
- import org.springframework.beans.factory.xml.ParserContext;
- import org.springframework.util.xml.DomUtils;
- import org.w3c.dom.Element;
-
- import java.util.List;
-
- public class ComponentBeanDefinitionParser extends AbstractBeanDefinitionParser {
-
- protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
- return parseComponentElement(element);
- }
-
- private static AbstractBeanDefinition parseComponentElement(Element element) {
- BeanDefinitionBuilder factory = BeanDefinitionBuilder.rootBeanDefinition(ComponentFactoryBean.class);
- factory.addPropertyValue("parent", parseComponent(element));
-
- List childElements = DomUtils.getChildElementsByTagName(element, "component");
- if (childElements != null && childElements.size() > 0) {
- parseChildComponents(childElements, factory);
- }
-
- return factory.getBeanDefinition();
- }
-
- private static BeanDefinition parseComponent(Element element) {
- BeanDefinitionBuilder component = BeanDefinitionBuilder.rootBeanDefinition(Component.class);
- component.addPropertyValue("name", element.getAttribute("name"));
- return component.getBeanDefinition();
- }
-
- private static void parseChildComponents(List childElements, BeanDefinitionBuilder factory) {
- ManagedList children = new ManagedList(childElements.size());
- for (Element element : childElements) {
- children.add(parseComponentElement(element));
- }
- factory.addPropertyValue("children", children);
- }
-
- }
-----
-
-Lastly, the various artifacts need to be registered with the Spring XML infrastructure.
-
-[literal]
-[subs="verbatim,quotes"]
-----
-# in 'META-INF/spring.handlers'
-http\://www.foo.com/schema/component=com.foo.ComponentNamespaceHandler
-----
-
-[literal]
-[subs="verbatim,quotes"]
-----
-# in 'META-INF/spring.schemas'
-http\://www.foo.com/schema/component/component.xsd=com/foo/component.xsd
-----
-
-
-
-[[extensible-xml-custom-just-attributes]]
-==== Custom attributes on 'normal' elements
-Writing your own custom parser and the associated artifacts isn't hard, but sometimes it
-is not the right thing to do. Consider the scenario where you need to add metadata to
-already existing bean definitions. In this case you certainly don't want to have to go
-off and write your own entire custom extension; rather you just want to add an
-additional attribute to the existing bean definition element.
-
-By way of another example, let's say that the service class that you are defining a bean
-definition for a service object that will (unknown to it) be accessing a clustered
-http://jcp.org/en/jsr/detail?id=107[JCache], and you want to ensure that the named
-JCache instance is eagerly started within the surrounding cluster:
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-----
-
-What we are going to do here is create another `BeanDefinition` when the
-`'jcache:cache-name'` attribute is parsed; this `BeanDefinition` will then initialize
-the named JCache for us. We will also modify the existing `BeanDefinition` for the
-`'checkingAccountService'` so that it will have a dependency on this new
-JCache-initializing `BeanDefinition`.
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- package com.foo;
-
- public class JCacheInitializer {
-
- private String name;
-
- public JCacheInitializer(String name) {
- this.name = name;
- }
-
- public void initialize() {
- // lots of JCache API calls to initialize the named cache...
- }
-
- }
-----
-
-Now onto the custom extension. Firstly, the authoring of the XSD schema describing the
-custom attribute (quite easy in this case).
-
-[source,xml,indent=0]
-[subs="verbatim,quotes"]
-----
-
-
-
-
-
-
-
-----
-
-Next, the associated `NamespaceHandler`.
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- package com.foo;
-
- import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
-
- public class JCacheNamespaceHandler extends NamespaceHandlerSupport {
-
- public void init() {
- super.registerBeanDefinitionDecoratorForAttribute("cache-name",
- new JCacheInitializingBeanDefinitionDecorator());
- }
-
- }
-----
-
-Next, the parser. Note that in this case, because we are going to be parsing an XML
-attribute, we write a `BeanDefinitionDecorator` rather than a `BeanDefinitionParser`.
-
-[source,java,indent=0]
-[subs="verbatim,quotes"]
-----
- package com.foo;
-
- import org.springframework.beans.factory.config.BeanDefinitionHolder;
- import org.springframework.beans.factory.support.AbstractBeanDefinition;
- import org.springframework.beans.factory.support.BeanDefinitionBuilder;
- import org.springframework.beans.factory.xml.BeanDefinitionDecorator;
- import org.springframework.beans.factory.xml.ParserContext;
- import org.w3c.dom.Attr;
- import org.w3c.dom.Node;
-
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.List;
-
- public class JCacheInitializingBeanDefinitionDecorator implements BeanDefinitionDecorator {
-
- private static final String[] EMPTY_STRING_ARRAY = new String[0];
-
- public BeanDefinitionHolder decorate(Node source, BeanDefinitionHolder holder,
- ParserContext ctx) {
- String initializerBeanName = registerJCacheInitializer(source, ctx);
- createDependencyOnJCacheInitializer(holder, initializerBeanName);
- return holder;
- }
-
- private void createDependencyOnJCacheInitializer(BeanDefinitionHolder holder,
- String initializerBeanName) {
- AbstractBeanDefinition definition = ((AbstractBeanDefinition) holder.getBeanDefinition());
- String[] dependsOn = definition.getDependsOn();
- if (dependsOn == null) {
- dependsOn = new String[]{initializerBeanName};
- } else {
- List dependencies = new ArrayList(Arrays.asList(dependsOn));
- dependencies.add(initializerBeanName);
- dependsOn = (String[]) dependencies.toArray(EMPTY_STRING_ARRAY);
- }
- definition.setDependsOn(dependsOn);
- }
-
- private String registerJCacheInitializer(Node source, ParserContext ctx) {
- String cacheName = ((Attr) source).getValue();
- String beanName = cacheName + "-initializer";
- if (!ctx.getRegistry().containsBeanDefinition(beanName)) {
- BeanDefinitionBuilder initializer = BeanDefinitionBuilder.rootBeanDefinition(JCacheInitializer.class);
- initializer.addConstructorArg(cacheName);
- ctx.getRegistry().registerBeanDefinition(beanName, initializer.getBeanDefinition());
- }
- return beanName;
- }
-
- }
-----
-
-Lastly, the various artifacts need to be registered with the Spring XML infrastructure.
-
-[literal]
-[subs="verbatim,quotes"]
-----
-# in 'META-INF/spring.handlers'
-http\://www.foo.com/schema/jcache=com.foo.JCacheNamespaceHandler
-----
-
-[literal]
-[subs="verbatim,quotes"]
-----
-# in 'META-INF/spring.schemas'
-http\://www.foo.com/schema/jcache/jcache.xsd=com/foo/jcache.xsd
-----
-
-
-
-
-[[extensible-xml-resources]]
-=== Further Resources
-Find below links to further resources concerning XML Schema and the extensible XML
-support described in this chapter.
-
-* The http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/[XML Schema Part 1: Structures
- Second Edition]
-* The http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/[XML Schema Part 2: Datatypes
- Second Edition]
-
-
-
-
-
-[[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]]
-=== 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.
-|===
-
-
-
-
-
-[[spring-form.tld]]
-== spring-form.tld
-
-
-
-
-[[spring-form.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-form.tld` tag library.
-
-* <>
-* <>
-* <>
-* <>
-* <>
-* <>
-* <>
-* <>
-* <>
-* <>
-* <>
-* <>
-* <>
-* <>
-
-
-
-
-[[spring-form.tld.checkbox]]
-=== the checkbox tag
-
-Renders an HTML 'input' tag with type 'checkbox'.
-
-[[spring-form.tld.checkbox.attrs.tbl]]
-.Attributes
-[cols="1,1,1,3"]
-|===
-| Attribute| Required?| Runtime Expression?| Description
-
-| accesskey
-| false
-| true
-| HTML Standard Attribute
-
-| cssClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute
-
-| cssErrorClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute. Used when the bound field has errors.
-
-| cssStyle
-| false
-| true
-| Equivalent to "style" - HTML Optional Attribute
-
-| dir
-| false
-| true
-| HTML Standard Attribute
-
-| disabled
-| false
-| true
-| HTML Optional Attribute. Setting the value of this attribute to 'true' (without the
- quotes) will disable the HTML element.
-
-| htmlEscape
-| false
-| true
-| Enable/disable HTML escaping of rendered values.
-
-| id
-| false
-| true
-| HTML Standard Attribute
-
-| label
-| false
-| true
-| Value to be displayed as part of the tag
-
-| lang
-| false
-| true
-| HTML Standard Attribute
-
-| onblur
-| false
-| true
-| HTML Event Attribute
-
-| onchange
-| false
-| true
-| HTML Event Attribute
-
-| onclick
-| false
-| true
-| HTML Event Attribute
-
-| ondblclick
-| false
-| true
-| HTML Event Attribute
-
-| onfocus
-| false
-| true
-| HTML Event Attribute
-
-| onkeydown
-| false
-| true
-| HTML Event Attribute
-
-| onkeypress
-| false
-| true
-| HTML Event Attribute
-
-| onkeyup
-| false
-| true
-| HTML Event Attribute
-
-| onmousedown
-| false
-| true
-| HTML Event Attribute
-
-| onmousemove
-| false
-| true
-| HTML Event Attribute
-
-| onmouseout
-| false
-| true
-| HTML Event Attribute
-
-| onmouseover
-| false
-| true
-| HTML Event Attribute
-
-| onmouseup
-| false
-| true
-| HTML Event Attribute
-
-| path
-| true
-| true
-| Path to property for data binding
-
-| tabindex
-| false
-| true
-| HTML Standard Attribute
-
-| title
-| false
-| true
-| HTML Standard Attribute
-
-| value
-| false
-| true
-| HTML Optional Attribute
-|===
-
-
-
-
-[[spring-form.tld.checkboxes]]
-=== the checkboxes tag
-
-Renders multiple HTML 'input' tags with type 'checkbox'.
-
-[[spring-form.tld.checkboxes.table]]
-.Attributes
-[cols="1,1,1,3"]
-|===
-| Attribute| Required?| Runtime Expression?| Description
-
-| accesskey
-| false
-| true
-| HTML Standard Attribute
-
-| cssClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute
-
-| cssErrorClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute. Used when the bound field has errors.
-
-| cssStyle
-| false
-| true
-| Equivalent to "style" - HTML Optional Attribute
-
-| delimiter
-| false
-| true
-| Delimiter to use between each 'input' tag with type 'checkbox'. There is no delimiter
- by default.
-
-| dir
-| false
-| true
-| HTML Standard Attribute
-
-| disabled
-| false
-| true
-| HTML Optional Attribute. Setting the value of this attribute to 'true' (without the
- quotes) will disable the HTML element.
-
-| element
-| false
-| true
-| Specifies the HTML element that is used to enclose each 'input' tag with type
- 'checkbox'. Defaults to 'span'.
-
-| htmlEscape
-| false
-| true
-| Enable/disable HTML escaping of rendered values.
-
-| id
-| false
-| true
-| HTML Standard Attribute
-
-| itemLabel
-| false
-| true
-| Value to be displayed as part of the 'input' tags with type 'checkbox'
-
-| items
-| true
-| true
-| The Collection, Map or array of objects used to generate the 'input' tags with type
- 'checkbox'
-
-| itemValue
-| false
-| true
-| Name of the property mapped to 'value' attribute of the 'input' tags with type
- 'checkbox'
-
-| lang
-| false
-| true
-| HTML Standard Attribute
-
-| onblur
-| false
-| true
-| HTML Event Attribute
-
-| onchange
-| false
-| true
-| HTML Event Attribute
-
-| onclick
-| false
-| true
-| HTML Event Attribute
-
-| ondblclick
-| false
-| true
-| HTML Event Attribute
-
-| onfocus
-| false
-| true
-| HTML Event Attribute
-
-| onkeydown
-| false
-| true
-| HTML Event Attribute
-
-| onkeypress
-| false
-| true
-| HTML Event Attribute
-
-| onkeyup
-| false
-| true
-| HTML Event Attribute
-
-| onmousedown
-| false
-| true
-| HTML Event Attribute
-
-| onmousemove
-| false
-| true
-| HTML Event Attribute
-
-| onmouseout
-| false
-| true
-| HTML Event Attribute
-
-| onmouseover
-| false
-| true
-| HTML Event Attribute
-
-| onmouseup
-| false
-| true
-| HTML Event Attribute
-
-| path
-| true
-| true
-| Path to property for data binding
-
-| tabindex
-| false
-| true
-| HTML Standard Attribute
-
-| title
-| false
-| true
-| HTML Standard Attribute
-|===
-
-
-
-
-[[spring-form.tld.errors]]
-=== the errors tag
-
-Renders field errors in an HTML 'span' tag.
-
-[[spring-form.tld.errors.table]]
-.Attributes
-[cols="1,1,1,3"]
-|===
-| Attribute| Required?| Runtime Expression?| Description
-
-| cssClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute
-
-| cssStyle
-| false
-| true
-| Equivalent to "style" - HTML Optional Attribute
-
-| delimiter
-| false
-| true
-| Delimiter for displaying multiple error messages. Defaults to the br tag.
-
-| dir
-| false
-| true
-| HTML Standard Attribute
-
-| element
-| false
-| true
-| Specifies the HTML element that is used to render the enclosing errors.
-
-| htmlEscape
-| false
-| true
-| Enable/disable HTML escaping of rendered values.
-
-| id
-| false
-| true
-| HTML Standard Attribute
-
-| lang
-| false
-| true
-| HTML Standard Attribute
-
-| onclick
-| false
-| true
-| HTML Event Attribute
-
-| ondblclick
-| false
-| true
-| HTML Event Attribute
-
-| onkeydown
-| false
-| true
-| HTML Event Attribute
-
-| onkeypress
-| false
-| true
-| HTML Event Attribute
-
-| onkeyup
-| false
-| true
-| HTML Event Attribute
-
-| onmousedown
-| false
-| true
-| HTML Event Attribute
-
-| onmousemove
-| false
-| true
-| HTML Event Attribute
-
-| onmouseout
-| false
-| true
-| HTML Event Attribute
-
-| onmouseover
-| false
-| true
-| HTML Event Attribute
-
-| onmouseup
-| false
-| true
-| HTML Event Attribute
-
-| path
-| false
-| true
-| Path to errors object for data binding
-
-| tabindex
-| false
-| true
-| HTML Standard Attribute
-
-| title
-| false
-| true
-| HTML Standard Attribute
-|===
-
-
-
-
-[[spring-form.tld.form]]
-=== the form tag
-
-Renders an HTML 'form' tag and exposes a binding path to inner tags for binding.
-
-[[spring-form.tld.form.table]]
-.Attributes
-[cols="1,1,1,3"]
-|===
-| Attribute| Required?| Runtime Expression?| Description
-
-| acceptCharset
-| false
-| true
-| Specifies the list of character encodings for input data that is accepted by the
- server processing this form. The value is a space- and/or comma-delimited list of
- charset values. The client must interpret this list as an exclusive-or list, i.e., the
- server is able to accept any single character encoding per entity received.
-
-| action
-| false
-| true
-| HTML Required Attribute
-
-| commandName
-| false
-| true
-| Name of the model attribute under which the form object is exposed. Defaults to
- 'command'.
-
-| cssClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute
-
-| cssStyle
-| false
-| true
-| Equivalent to "style" - HTML Optional Attribute
-
-| dir
-| false
-| true
-| HTML Standard Attribute
-
-| enctype
-| false
-| true
-| HTML Optional Attribute
-
-| htmlEscape
-| false
-| true
-| Enable/disable HTML escaping of rendered values.
-
-| id
-| false
-| true
-| HTML Standard Attribute
-
-| lang
-| false
-| true
-| HTML Standard Attribute
-
-| method
-| false
-| true
-| HTML Optional Attribute
-
-| modelAttribute
-| false
-| true
-| Name of the model attribute under which the form object is exposed. Defaults to
- 'command'.
-
-| name
-| false
-| true
-| HTML Standard Attribute - added for backwards compatibility cases
-
-| onclick
-| false
-| true
-| HTML Event Attribute
-
-| ondblclick
-| false
-| true
-| HTML Event Attribute
-
-| onkeydown
-| false
-| true
-| HTML Event Attribute
-
-| onkeypress
-| false
-| true
-| HTML Event Attribute
-
-| onkeyup
-| false
-| true
-| HTML Event Attribute
-
-| onmousedown
-| false
-| true
-| HTML Event Attribute
-
-| onmousemove
-| false
-| true
-| HTML Event Attribute
-
-| onmouseout
-| false
-| true
-| HTML Event Attribute
-
-| onmouseover
-| false
-| true
-| HTML Event Attribute
-
-| onmouseup
-| false
-| true
-| HTML Event Attribute
-
-| onreset
-| false
-| true
-| HTML Event Attribute
-
-| onsubmit
-| false
-| true
-| HTML Event Attribute
-
-| target
-| false
-| true
-| HTML Optional Attribute
-
-| title
-| false
-| true
-| HTML Standard Attribute
-|===
-
-
-
-
-[[spring-form.tld.hidden]]
-=== the hidden tag
-
-Renders an HTML 'input' tag with type 'hidden' using the bound value.
-
-[[spring-form.tld.hidden.table]]
-.Attributes
-[cols="1,1,1,3"]
-|===
-| Attribute| Required?| Runtime Expression?| Description
-
-| htmlEscape
-| false
-| true
-| Enable/disable HTML escaping of rendered values.
-
-| id
-| false
-| true
-| HTML Standard Attribute
-
-| path
-| true
-| true
-| Path to property for data binding
-|===
-
-
-
-
-[[spring-form.tld.input]]
-=== the input tag
-
-Renders an HTML 'input' tag with type 'text' using the bound value.
-
-[[spring-form.tld.input.table]]
-.Attributes
-[cols="1,1,1,3"]
-|===
-| Attribute| Required?| Runtime Expression?| Description
-
-| accesskey
-| false
-| true
-| HTML Standard Attribute
-
-| alt
-| false
-| true
-| HTML Optional Attribute
-
-| autocomplete
-| false
-| true
-| Common Optional Attribute
-
-| cssClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute
-
-| cssErrorClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute. Used when the bound field has errors.
-
-| cssStyle
-| false
-| true
-| Equivalent to "style" - HTML Optional Attribute
-
-| dir
-| false
-| true
-| HTML Standard Attribute
-
-| disabled
-| false
-| true
-| HTML Optional Attribute. Setting the value of this attribute to 'true' (without the
- quotes) will disable the HTML element.
-
-| htmlEscape
-| false
-| true
-| Enable/disable HTML escaping of rendered values.
-
-| id
-| false
-| true
-| HTML Standard Attribute
-
-| lang
-| false
-| true
-| HTML Standard Attribute
-
-| maxlength
-| false
-| true
-| HTML Optional Attribute
-
-| onblur
-| false
-| true
-| HTML Event Attribute
-
-| onchange
-| false
-| true
-| HTML Event Attribute
-
-| onclick
-| false
-| true
-| HTML Event Attribute
-
-| ondblclick
-| false
-| true
-| HTML Event Attribute
-
-| onfocus
-| false
-| true
-| HTML Event Attribute
-
-| onkeydown
-| false
-| true
-| HTML Event Attribute
-
-| onkeypress
-| false
-| true
-| HTML Event Attribute
-
-| onkeyup
-| false
-| true
-| HTML Event Attribute
-
-| onmousedown
-| false
-| true
-| HTML Event Attribute
-
-| onmousemove
-| false
-| true
-| HTML Event Attribute
-
-| onmouseout
-| false
-| true
-| HTML Event Attribute
-
-| onmouseover
-| false
-| true
-| HTML Event Attribute
-
-| onmouseup
-| false
-| true
-| HTML Event Attribute
-
-| onselect
-| false
-| true
-| HTML Event Attribute
-
-| path
-| true
-| true
-| Path to property for data binding
-
-| readonly
-| false
-| true
-| HTML Optional Attribute. Setting the value of this attribute to 'true' (without the
- quotes) will make the HTML element readonly.
-
-| size
-| false
-| true
-| HTML Optional Attribute
-
-| tabindex
-| false
-| true
-| HTML Standard Attribute
-
-| title
-| false
-| true
-| HTML Standard Attribute
-|===
-
-
-
-
-[[spring-form.tld.label]]
-=== the label tag
-
-Renders a form field label in an HTML 'label' tag.
-
-[[spring-form.tld.label.table]]
-[cols="1,1,1,3"]
-.Attributes
-|===
-| Attribute| Required?| Runtime Expression?| Description
-
-| cssClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute.
-
-| cssErrorClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute. Used only when errors are present.
-
-| cssStyle
-| false
-| true
-| Equivalent to "style" - HTML Optional Attribute
-
-| dir
-| false
-| true
-| HTML Standard Attribute
-
-| for
-| false
-| true
-| HTML Standard Attribute
-
-| htmlEscape
-| false
-| true
-| Enable/disable HTML escaping of rendered values.
-
-| id
-| false
-| true
-| HTML Standard Attribute
-
-| lang
-| false
-| true
-| HTML Standard Attribute
-
-| onclick
-| false
-| true
-| HTML Event Attribute
-
-| ondblclick
-| false
-| true
-| HTML Event Attribute
-
-| onkeydown
-| false
-| true
-| HTML Event Attribute
-
-| onkeypress
-| false
-| true
-| HTML Event Attribute
-
-| onkeyup
-| false
-| true
-| HTML Event Attribute
-
-| onmousedown
-| false
-| true
-| HTML Event Attribute
-
-| onmousemove
-| false
-| true
-| HTML Event Attribute
-
-| onmouseout
-| false
-| true
-| HTML Event Attribute
-
-| onmouseover
-| false
-| true
-| HTML Event Attribute
-
-| onmouseup
-| false
-| true
-| HTML Event Attribute
-
-| path
-| true
-| true
-| Path to errors object for data binding
-
-| tabindex
-| false
-| true
-| HTML Standard Attribute
-
-| title
-| false
-| true
-| HTML Standard Attribute
-|===
-
-
-
-
-[[spring-form.tld.option]]
-=== the option tag
-
-Renders a single HTML 'option'. Sets 'selected' as appropriate based on bound value.
-
-[[spring-form.tld.option.table]]
-.Attributes
-[cols="1,1,1,3"]
-|===
-| Attribute| Required?| Runtime Expression?| Description
-
-| cssClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute
-
-| cssErrorClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute. Used when the bound field has errors.
-
-| cssStyle
-| false
-| true
-| Equivalent to "style" - HTML Optional Attribute
-
-| dir
-| false
-| true
-| HTML Standard Attribute
-
-| disabled
-| false
-| true
-| HTML Optional Attribute. Setting the value of this attribute to 'true' (without the
- quotes) will disable the HTML element.
-
-| htmlEscape
-| false
-| true
-| Enable/disable HTML escaping of rendered values.
-
-| id
-| false
-| true
-| HTML Standard Attribute
-
-| label
-| false
-| true
-| HTML Optional Attribute
-
-| lang
-| false
-| true
-| HTML Standard Attribute
-
-| onclick
-| false
-| true
-| HTML Event Attribute
-
-| ondblclick
-| false
-| true
-| HTML Event Attribute
-
-| onkeydown
-| false
-| true
-| HTML Event Attribute
-
-| onkeypress
-| false
-| true
-| HTML Event Attribute
-
-| onkeyup
-| false
-| true
-| HTML Event Attribute
-
-| onmousedown
-| false
-| true
-| HTML Event Attribute
-
-| onmousemove
-| false
-| true
-| HTML Event Attribute
-
-| onmouseout
-| false
-| true
-| HTML Event Attribute
-
-| onmouseover
-| false
-| true
-| HTML Event Attribute
-
-| onmouseup
-| false
-| true
-| HTML Event Attribute
-
-| tabindex
-| false
-| true
-| HTML Standard Attribute
-
-| title
-| false
-| true
-| HTML Standard Attribute
-
-| value
-| true
-| true
-| HTML Optional Attribute
-|===
-
-
-
-
-[[spring-form.tld.options]]
-=== the options tag
-
-Renders a list of HTML 'option' tags. Sets 'selected' as appropriate based on bound value.
-
-[[spring-form.tld.options.table]]
-.Attributes
-[cols="1,1,1,3"]
-|===
-| Attribute| Required?| Runtime Expression?| Description
-
-| cssClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute
-
-| cssErrorClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute. Used when the bound field has errors.
-
-| cssStyle
-| false
-| true
-| Equivalent to "style" - HTML Optional Attribute
-
-| dir
-| false
-| true
-| HTML Standard Attribute
-
-| disabled
-| false
-| true
-| HTML Optional Attribute. Setting the value of this attribute to 'true' (without the
- quotes) will disable the HTML element.
-
-| htmlEscape
-| false
-| true
-| Enable/disable HTML escaping of rendered values.
-
-| id
-| false
-| true
-| HTML Standard Attribute
-
-| itemLabel
-| false
-| true
-| Name of the property mapped to the inner text of the 'option' tag
-
-| items
-| true
-| true
-| The Collection, Map or array of objects used to generate the inner 'option' tags
-
-| itemValue
-| false
-| true
-| Name of the property mapped to 'value' attribute of the 'option' tag
-
-| lang
-| false
-| true
-| HTML Standard Attribute
-
-| onclick
-| false
-| true
-| HTML Event Attribute
-
-| ondblclick
-| false
-| true
-| HTML Event Attribute
-
-| onkeydown
-| false
-| true
-| HTML Event Attribute
-
-| onkeypress
-| false
-| true
-| HTML Event Attribute
-
-| onkeyup
-| false
-| true
-| HTML Event Attribute
-
-| onmousedown
-| false
-| true
-| HTML Event Attribute
-
-| onmousemove
-| false
-| true
-| HTML Event Attribute
-
-| onmouseout
-| false
-| true
-| HTML Event Attribute
-
-| onmouseover
-| false
-| true
-| HTML Event Attribute
-
-| onmouseup
-| false
-| true
-| HTML Event Attribute
-
-| tabindex
-| false
-| true
-| HTML Standard Attribute
-
-| title
-| false
-| true
-| HTML Standard Attribute
-|===
-
-
-
-
-[[spring-form.tld.password]]
-=== the password tag
-
-Renders an HTML 'input' tag with type 'password' using the bound value.
-
-[[spring-form.tld.password.table]]
-.Attributes
-[cols="1,1,1,3"]
-|===
-| Attribute| Required?| Runtime Expression?| Description
-
-| accesskey
-| false
-| true
-| HTML Standard Attribute
-
-| alt
-| false
-| true
-| HTML Optional Attribute
-
-| autocomplete
-| false
-| true
-| Common Optional Attribute
-
-| cssClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute
-
-| cssErrorClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute. Used when the bound field has errors.
-
-| cssStyle
-| false
-| true
-| Equivalent to "style" - HTML Optional Attribute
-
-| dir
-| false
-| true
-| HTML Standard Attribute
-
-| disabled
-| false
-| true
-| HTML Optional Attribute. Setting the value of this attribute to 'true' (without the
- quotes) will disable the HTML element.
-
-| htmlEscape
-| false
-| true
-| Enable/disable HTML escaping of rendered values.
-
-| id
-| false
-| true
-| HTML Standard Attribute
-
-| lang
-| false
-| true
-| HTML Standard Attribute
-
-| maxlength
-| false
-| true
-| HTML Optional Attribute
-
-| onblur
-| false
-| true
-| HTML Event Attribute
-
-| onchange
-| false
-| true
-| HTML Event Attribute
-
-| onclick
-| false
-| true
-| HTML Event Attribute
-
-| ondblclick
-| false
-| true
-| HTML Event Attribute
-
-| onfocus
-| false
-| true
-| HTML Event Attribute
-
-| onkeydown
-| false
-| true
-| HTML Event Attribute
-
-| onkeypress
-| false
-| true
-| HTML Event Attribute
-
-| onkeyup
-| false
-| true
-| HTML Event Attribute
-
-| onmousedown
-| false
-| true
-| HTML Event Attribute
-
-| onmousemove
-| false
-| true
-| HTML Event Attribute
-
-| onmouseout
-| false
-| true
-| HTML Event Attribute
-
-| onmouseover
-| false
-| true
-| HTML Event Attribute
-
-| onmouseup
-| false
-| true
-| HTML Event Attribute
-
-| onselect
-| false
-| true
-| HTML Event Attribute
-
-| path
-| true
-| true
-| Path to property for data binding
-
-| readonly
-| false
-| true
-| HTML Optional Attribute. Setting the value of this attribute to 'true' (without the
- quotes) will make the HTML element readonly.
-
-| showPassword
-| false
-| true
-| Is the password value to be shown? Defaults to false.
-
-| size
-| false
-| true
-| HTML Optional Attribute
-
-| tabindex
-| false
-| true
-| HTML Standard Attribute
-
-| title
-| false
-| true
-| HTML Standard Attribute
-|===
-
-
-
-
-[[spring-form.tld.radiobutton]]
-=== the radiobutton tag
-
-Renders an HTML 'input' tag with type 'radio'.
-
-[[spring-form.tld.radiobutton.table]]
-.Attributes
-[cols="1,1,1,3"]
-|===
-| Attribute| Required?| Runtime Expression?| Description
-
-| accesskey
-| false
-| true
-| HTML Standard Attribute
-
-| cssClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute
-
-| cssErrorClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute. Used when the bound field has errors.
-
-| cssStyle
-| false
-| true
-| Equivalent to "style" - HTML Optional Attribute
-
-| dir
-| false
-| true
-| HTML Standard Attribute
-
-| disabled
-| false
-| true
-| HTML Optional Attribute. Setting the value of this attribute to 'true' (without the
- quotes) will disable the HTML element.
-
-| htmlEscape
-| false
-| true
-| Enable/disable HTML escaping of rendered values.
-
-| id
-| false
-| true
-| HTML Standard Attribute
-
-| label
-| false
-| true
-| Value to be displayed as part of the tag
-
-| lang
-| false
-| true
-| HTML Standard Attribute
-
-| onblur
-| false
-| true
-| HTML Event Attribute
-
-| onchange
-| false
-| true
-| HTML Event Attribute
-
-| onclick
-| false
-| true
-| HTML Event Attribute
-
-| ondblclick
-| false
-| true
-| HTML Event Attribute
-
-| onfocus
-| false
-| true
-| HTML Event Attribute
-
-| onkeydown
-| false
-| true
-| HTML Event Attribute
-
-| onkeypress
-| false
-| true
-| HTML Event Attribute
-
-| onkeyup
-| false
-| true
-| HTML Event Attribute
-
-| onmousedown
-| false
-| true
-| HTML Event Attribute
-
-| onmousemove
-| false
-| true
-| HTML Event Attribute
-
-| onmouseout
-| false
-| true
-| HTML Event Attribute
-
-| onmouseover
-| false
-| true
-| HTML Event Attribute
-
-| onmouseup
-| false
-| true
-| HTML Event Attribute
-
-| path
-| true
-| true
-| Path to property for data binding
-
-| tabindex
-| false
-| true
-| HTML Standard Attribute
-
-| title
-| false
-| true
-| HTML Standard Attribute
-
-| value
-| false
-| true
-| HTML Optional Attribute
-|===
-
-
-
-
-[[spring-form.tld.radiobuttons]]
-=== the radiobuttons tag
-
-Renders multiple HTML 'input' tags with type 'radio'.
-
-[[spring-form.tld.radiobuttons.table]]
-.Attributes
-[cols="1,1,1,3"]
-|===
-| Attribute| Required?| Runtime Expression?| Description
-
-| accesskey
-| false
-| true
-| HTML Standard Attribute
-
-| cssClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute
-
-| cssErrorClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute. Used when the bound field has errors.
-
-| cssStyle
-| false
-| true
-| Equivalent to "style" - HTML Optional Attribute
-
-| delimiter
-| false
-| true
-| Delimiter to use between each 'input' tag with type 'radio'. There is no delimiter by
- default.
-
-| dir
-| false
-| true
-| HTML Standard Attribute
-
-| disabled
-| false
-| true
-| HTML Optional Attribute. Setting the value of this attribute to 'true' (without the
- quotes) will disable the HTML element.
-
-| element
-| false
-| true
-| Specifies the HTML element that is used to enclose each 'input' tag with type 'radio'.
- Defaults to 'span'.
-
-| htmlEscape
-| false
-| true
-| Enable/disable HTML escaping of rendered values.
-
-| id
-| false
-| true
-| HTML Standard Attribute
-
-| itemLabel
-| false
-| true
-| Value to be displayed as part of the 'input' tags with type 'radio'
-
-| items
-| true
-| true
-| The Collection, Map or array of objects used to generate the 'input' tags with type
- 'radio'
-
-| itemValue
-| false
-| true
-| Name of the property mapped to 'value' attribute of the 'input' tags with type 'radio'
-
-| lang
-| false
-| true
-| HTML Standard Attribute
-
-| onblur
-| false
-| true
-| HTML Event Attribute
-
-| onchange
-| false
-| true
-| HTML Event Attribute
-
-| onclick
-| false
-| true
-| HTML Event Attribute
-
-| ondblclick
-| false
-| true
-| HTML Event Attribute
-
-| onfocus
-| false
-| true
-| HTML Event Attribute
-
-| onkeydown
-| false
-| true
-| HTML Event Attribute
-
-| onkeypress
-| false
-| true
-| HTML Event Attribute
-
-| onkeyup
-| false
-| true
-| HTML Event Attribute
-
-| onmousedown
-| false
-| true
-| HTML Event Attribute
-
-| onmousemove
-| false
-| true
-| HTML Event Attribute
-
-| onmouseout
-| false
-| true
-| HTML Event Attribute
-
-| onmouseover
-| false
-| true
-| HTML Event Attribute
-
-| onmouseup
-| false
-| true
-| HTML Event Attribute
-
-| path
-| true
-| true
-| Path to property for data binding
-
-| tabindex
-| false
-| true
-| HTML Standard Attribute
-
-| title
-| false
-| true
-| HTML Standard Attribute
-|===
-
-
-
-
-[[spring-form.tld.select]]
-=== the select tag
-
-Renders an HTML 'select' element. Supports databinding to the selected option.
-
-[[spring-form.tld.select.table]]
-.Attributes
-[cols="1,1,1,3"]
-|===
-| Attribute| Required?| Runtime Expression?| Description
-
-| accesskey
-| false
-| true
-| HTML Standard Attribute
-
-| cssClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute
-
-| cssErrorClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute. Used when the bound field has errors.
-
-| cssStyle
-| false
-| true
-| Equivalent to "style" - HTML Optional Attribute
-
-| dir
-| false
-| true
-| HTML Standard Attribute
-
-| disabled
-| false
-| true
-| HTML Optional Attribute. Setting the value of this attribute to 'true' (without the
- quotes) will disable the HTML element.
-
-| htmlEscape
-| false
-| true
-| Enable/disable HTML escaping of rendered values.
-
-| id
-| false
-| true
-| HTML Standard Attribute
-
-| itemLabel
-| false
-| true
-| Name of the property mapped to the inner text of the 'option' tag
-
-| items
-| false
-| true
-| The Collection, Map or array of objects used to generate the inner 'option' tags
-
-| itemValue
-| false
-| true
-| Name of the property mapped to 'value' attribute of the 'option' tag
-
-| lang
-| false
-| true
-| HTML Standard Attribute
-
-| multiple
-| false
-| true
-| HTML Optional Attribute
-
-| onblur
-| false
-| true
-| HTML Event Attribute
-
-| onchange
-| false
-| true
-| HTML Event Attribute
-
-| onclick
-| false
-| true
-| HTML Event Attribute
-
-| ondblclick
-| false
-| true
-| HTML Event Attribute
-
-| onfocus
-| false
-| true
-| HTML Event Attribute
-
-| onkeydown
-| false
-| true
-| HTML Event Attribute
-
-| onkeypress
-| false
-| true
-| HTML Event Attribute
-
-| onkeyup
-| false
-| true
-| HTML Event Attribute
-
-| onmousedown
-| false
-| true
-| HTML Event Attribute
-
-| onmousemove
-| false
-| true
-| HTML Event Attribute
-
-| onmouseout
-| false
-| true
-| HTML Event Attribute
-
-| onmouseover
-| false
-| true
-| HTML Event Attribute
-
-| onmouseup
-| false
-| true
-| HTML Event Attribute
-
-| path
-| true
-| true
-| Path to property for data binding
-
-| size
-| false
-| true
-| HTML Optional Attribute
-
-| tabindex
-| false
-| true
-| HTML Standard Attribute
-
-| title
-| false
-| true
-| HTML Standard Attribute
-|===
-
-
-
-
-[[spring-form.tld.textarea]]
-=== the textarea tag
-
-Renders an HTML 'textarea'.
-
-[[spring-form.tld.textarea.table]]
-.Attributes
-[cols="1,1,1,3"]
-|===
-| Attribute| Required?| Runtime Expression?| Description
-
-| accesskey
-| false
-| true
-| HTML Standard Attribute
-
-| cols
-| false
-| true
-| HTML Required Attribute
-
-| cssClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute
-
-| cssErrorClass
-| false
-| true
-| Equivalent to "class" - HTML Optional Attribute. Used when the bound field has errors.
-
-| cssStyle
-| false
-| true
-| Equivalent to "style" - HTML Optional Attribute
-
-| dir
-| false
-| true
-| HTML Standard Attribute
-
-| disabled
-| false
-| true
-| HTML Optional Attribute. Setting the value of this attribute to 'true' (without the
- quotes) will disable the HTML element.
-
-| htmlEscape
-| false
-| true
-| Enable/disable HTML escaping of rendered values.
-
-| id
-| false
-| true
-| HTML Standard Attribute
-
-| lang
-| false
-| true
-| HTML Standard Attribute
-
-| onblur
-| false
-| true
-| HTML Event Attribute
-
-| onchange
-| false
-| true
-| HTML Event Attribute
-
-| onclick
-| false
-| true
-| HTML Event Attribute
-
-| ondblclick
-| false
-| true
-| HTML Event Attribute
-
-| onfocus
-| false
-| true
-| HTML Event Attribute
-
-| onkeydown
-| false
-| true
-| HTML Event Attribute
-
-| onkeypress
-| false
-| true
-| HTML Event Attribute
-
-| onkeyup
-| false
-| true
-| HTML Event Attribute
-
-| onmousedown
-| false
-| true
-| HTML Event Attribute
-
-| onmousemove
-| false
-| true
-| HTML Event Attribute
-
-| onmouseout
-| false
-| true
-| HTML Event Attribute
-
-| onmouseover
-| false
-| true
-| HTML Event Attribute
-
-| onmouseup
-| false
-| true
-| HTML Event Attribute
-
-| onselect
-| false
-| true
-| HTML Event Attribute
-
-| path
-| true
-| true
-| Path to property for data binding
-
-| readonly
-| false
-| true
-| HTML Optional Attribute. Setting the value of this attribute to 'true' (without the
- quotes) will make the HTML element readonly.
-
-| rows
-| false
-| true
-| HTML Required Attribute
-
-| tabindex
-| false
-| true
-| HTML Standard Attribute
-
-| title
-| false
-| true
-| HTML Standard Attribute
-|===
diff --git a/src/asciidoc/beans.adoc b/src/asciidoc/beans.adoc
new file mode 100644
index 000000000000..445d3a63fef8
--- /dev/null
+++ b/src/asciidoc/beans.adoc
@@ -0,0 +1,7892 @@
+[[beans]]
+== The IoC container
+
+
+
+
+[[beans-introduction]]
+=== Introduction to the Spring IoC container and beans
+This chapter covers the Spring Framework implementation of the Inversion of Control
+(IoC) footnote:[See pass:specialcharacters,macros[<>] ] principle. IoC
+is also known as __dependency injection__ (DI). It is a process whereby objects define
+their dependencies, that is, the other objects they work with, only through constructor
+arguments, arguments to a factory method, or properties that are set on the object
+instance after it is constructed or returned from a factory method. The container then
+__injects__ those dependencies when it creates the bean. This process is fundamentally
+the inverse, hence the name __Inversion of Control__ (IoC), of the bean itself
+controlling the instantiation or location of its dependencies by using direct
+construction of classes, or a mechanism such as the __Service Locator__ pattern.
+
+The `org.springframework.beans` and `org.springframework.context` packages are the basis
+for Spring Framework's IoC container. The
+{javadoc-baseurl}/org/springframework/beans/factory/BeanFactory.html[`BeanFactory`]
+interface provides an advanced configuration mechanism capable of managing any type of
+object.
+{javadoc-baseurl}/org/springframework/context/ApplicationContext.html[`ApplicationContext`]
+is a sub-interface of `BeanFactory`. It adds easier integration with Spring's AOP
+features; message resource handling (for use in internationalization), event
+publication; and application-layer specific contexts such as the `WebApplicationContext`
+for use in web applications.
+
+In short, the `BeanFactory` provides the configuration framework and basic
+functionality, and the `ApplicationContext` adds more enterprise-specific functionality.
+The `ApplicationContext` is a complete superset of the `BeanFactory`, and is used
+exclusively in this chapter in descriptions of Spring's IoC container. For more
+information on using the `BeanFactory` instead of the `ApplicationContext,` refer to
+<>.
+
+In Spring, the objects that form the backbone of your application and that are managed
+by the Spring IoC __container__ are called __beans__. A bean is an object that is
+instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, a
+bean is simply one of many objects in your application. Beans, and the __dependencies__
+among them, are reflected in the __configuration metadata__ used by a container.
+
+
+
+
+[[beans-basics]]
+=== Container overview
+The interface `org.springframework.context.ApplicationContext` represents the Spring IoC
+container and is responsible for instantiating, configuring, and assembling the
+aforementioned beans. The container gets its instructions on what objects to
+instantiate, configure, and assemble by reading configuration metadata. The
+configuration metadata is represented in XML, Java annotations, or Java code. It allows
+you to express the objects that compose your application and the rich interdependencies
+between such objects.
+
+Several implementations of the `ApplicationContext` interface are supplied
+out-of-the-box with Spring. In standalone applications it is common to create an
+instance of
+{javadoc-baseurl}/org/springframework/context/support/ClassPathXmlApplicationContext.html[`ClassPathXmlApplicationContext`]
+or {javadoc-baseurl}/org/springframework/context/support/FileSystemXmlApplicationContext.html[`FileSystemXmlApplicationContext`].
+ While XML has been the traditional format for defining configuration metadata you can
+instruct the container to use Java annotations or code as the metadata format by
+providing a small amount of XML configuration to declaratively enable support for these
+additional metadata formats.
+
+In most application scenarios, explicit user code is not required to instantiate one or
+more instances of a Spring IoC container. For example, in a web application scenario, a
+simple eight (or so) lines of boilerplate web descriptor XML in the `web.xml` file
+of the application will typically suffice (see <>). If you are using the
+https://spring.io/tools/sts[Spring Tool Suite] Eclipse-powered development
+environment this boilerplate configuration can be easily created with few mouse clicks or
+keystrokes.
+
+The following diagram is a high-level view of how Spring works. Your application classes
+are combined with configuration metadata so that after the `ApplicationContext` is
+created and initialized, you have a fully configured and executable system or
+application.
+
+.The Spring IoC container
+image::images/container-magic.png[width=250]
+
+
+
+[[beans-factory-metadata]]
+==== Configuration metadata
+As the preceding diagram shows, the Spring IoC container consumes a form of
+__configuration metadata__; this configuration metadata represents how you as an
+application developer tell the Spring container to instantiate, configure, and assemble
+the objects in your application.
+
+Configuration metadata is traditionally supplied in a simple and intuitive XML format,
+which is what most of this chapter uses to convey key concepts and features of the
+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
+<> for their Spring applications.
+====
+
+For information about using other forms of metadata with the Spring container, see:
+
+* <>: Spring 2.5 introduced
+ support for annotation-based configuration metadata.
+* <>: Starting with Spring 3.0, many features
+ provided by the Spring JavaConfig project became part of the core Spring Framework.
+ Thus you can define beans external to your application classes by using Java rather
+ than XML files. To use these new features, see the `@Configuration`, `@Bean`, `@Import`
+ and `@DependsOn` annotations.
+
+Spring configuration consists of at least one and typically more than one bean
+definition that the container must manage. XML-based configuration metadata shows these
+beans configured as `` elements inside a top-level `` element. Java
+configuration typically uses `@Bean` annotated methods within a `@Configuration` class.
+
+These bean definitions correspond to the actual objects that make up your application.
+Typically you define service layer objects, data access objects (DAOs), presentation
+objects such as Struts `Action` instances, infrastructure objects such as Hibernate
+`SessionFactories`, JMS `Queues`, and so forth. Typically one does not configure
+fine-grained domain objects in the container, because it is usually the responsibility
+of DAOs and business logic to create and load domain objects. However, you can use
+Spring's integration with AspectJ to configure objects that have been created outside
+the control of an IoC container. See <>.
+
+The following example shows the basic structure of XML-based configuration metadata:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+----
+
+The `id` attribute is a string that you use to identify the individual bean definition.
+The `class` attribute defines the type of the bean and uses the fully qualified
+classname. The value of the id attribute refers to collaborating objects. The XML for
+referring to collaborating objects is not shown in this example; see
+<> for more information.
+
+
+
+[[beans-factory-instantiation]]
+==== Instantiating a container
+Instantiating a Spring IoC container is straightforward. The location path or paths
+supplied to an `ApplicationContext` constructor are actually resource strings that allow
+the container to load configuration metadata from a variety of external resources such
+as the local file system, from the Java `CLASSPATH`, and so on.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ ApplicationContext context =
+ new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});
+----
+
+[NOTE]
+====
+After you learn about Spring's IoC container, you may want to know more about Spring's
+`Resource` abstraction, as described in <>, 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
+<>.
+====
+
+The following example shows the service layer objects `(services.xml)` configuration file:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+----
+
+The following example shows the data access objects `daos.xml` file:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+----
+
+In the preceding example, the service layer consists of the class `PetStoreServiceImpl`,
+and two data access objects of the type `JpaAccountDao` and `JpaItemDao` (based
+on the JPA Object/Relational mapping standard). The `property name` element refers to the
+name of the JavaBean property, and the `ref` element refers to the name of another bean
+definition. This linkage between `id` and `ref` elements expresses the dependency between
+collaborating objects. For details of configuring an object's dependencies, see
+<>.
+
+
+[[beans-factory-xml-import]]
+===== Composing XML-based configuration metadata
+It can be useful to have bean definitions span multiple XML files. Often each individual
+XML configuration file represents a logical layer or module in your architecture.
+
+You can use the application context constructor to load bean definitions from all these
+XML fragments. This constructor takes multiple `Resource` locations, as was shown in the
+previous section. Alternatively, use one or more occurrences of the `` element
+to load bean definitions from another file or files. For example:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+----
+
+In the preceding example, external bean definitions are loaded from three files:
+`services.xml`, `messageSource.xml`, and `themeSource.xml`. All location paths are
+relative to the definition file doing the importing, so `services.xml` must be in the
+same directory or classpath location as the file doing the importing, while
+`messageSource.xml` and `themeSource.xml` must be in a `resources` location below the
+location of the importing file. As you can see, a leading slash is ignored, but given
+that these paths are relative, it is better form not to use the slash at all. The
+contents of the files being imported, including the top level `` element, must
+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
+example, "classpath:../services.xml"), where the runtime resolution process chooses the
+"nearest" classpath root and then looks into its parent directory. Classpath
+configuration changes may lead to the choice of a different, incorrect directory.
+
+You can always use fully qualified resource locations instead of relative paths: for
+example, "file:C:/config/services.xml" or "classpath:/config/services.xml". However, be
+aware that you are coupling your application's configuration to specific absolute
+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.
+====
+
+
+
+[[beans-factory-client]]
+==== Using the container
+The `ApplicationContext` is the interface for an advanced factory capable of maintaining
+a registry of different beans and their dependencies. Using the method `T getBean(String
+name, Class requiredType)` you can retrieve instances of your beans.
+
+The `ApplicationContext` enables you to read bean definitions and access them as follows:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ // create and configure beans
+ ApplicationContext context =
+ new ClassPathXmlApplicationContext(new String[] {"services.xml", "daos.xml"});
+
+ // retrieve configured instance
+ PetStoreService service = context.getBean("petStore", PetStoreService.class);
+
+ // use configured instance
+ List userList = service.getUsernameList();
+----
+
+You use `getBean()` to retrieve instances of your beans. The `ApplicationContext`
+interface has a few other methods for retrieving beans, but ideally your application
+code should never use them. Indeed, your application code should have no calls to the
+`getBean()` method at all, and thus no dependency on Spring APIs at all. For example,
+Spring's integration with web frameworks provides for dependency injection for various
+web framework classes such as controllers and JSF-managed beans.
+
+
+
+
+[[beans-definition]]
+=== Bean overview
+A Spring IoC container manages one or more __beans__. These beans are created with the
+configuration metadata that you supply to the container, for example, in the form of XML
+`` definitions.
+
+Within the container itself, these bean definitions are represented as `BeanDefinition`
+objects, which contain (among other information) the following metadata:
+
+* __A package-qualified class name:__ typically the actual implementation class of the
+ bean being defined.
+* Bean behavioral configuration elements, which state how the bean should behave in the
+ container (scope, lifecycle callbacks, and so forth).
+* References to other beans that are needed for the bean to do its work; these
+ references are also called __collaborators__ or __dependencies__.
+* Other configuration settings to set in the newly created object, for example, the
+ number of connections to use in a bean that manages a connection pool, or the size
+ limit of the pool.
+
+This metadata translates to a set of properties that make up each bean definition.
+
+[[beans-factory-bean-definition-tbl]]
+.The bean definition
+|===
+| Property| Explained in...
+
+| class
+| <>
+
+| name
+| <>
+
+| scope
+| <>
+
+| constructor arguments
+| <>
+
+| properties
+| <>
+
+| autowiring mode
+| <>
+
+| lazy-initialization mode
+| <>
+
+| initialization method
+| <>
+
+| destruction method
+| <>
+|===
+
+In addition to bean definitions that contain information on how to create a specific
+bean, the `ApplicationContext` implementations also permit the registration of existing
+objects that are created outside the container, by users. This is done by accessing the
+ApplicationContext's BeanFactory via the method `getBeanFactory()` which returns the
+BeanFactory implementation `DefaultListableBeanFactory`. `DefaultListableBeanFactory`
+supports this registration through the methods `registerSingleton(..)` and
+`registerBeanDefinition(..)`. However, typical applications work solely with beans
+defined through metadata bean definitions.
+
+
+
+[[beans-beanname]]
+==== Naming beans
+Every bean has one or more identifiers. These identifiers must be unique within the
+container that hosts the bean. A bean usually has only one identifier, but if it
+requires more than one, the extra ones can be considered aliases.
+
+In XML-based configuration metadata, you use the `id` and/or `name` attributes
+to specify the bean identifier(s). The `id` attribute allows you to specify
+exactly one id. Conventionally these names are alphanumeric ('myBean',
+'fooService', etc.), but may contain special characters as well. If you want to
+introduce other aliases to the bean, you can also specify them in the `name`
+attribute, separated by a comma (`,`), semicolon (`;`), or white space. As a
+historical note, in versions prior to Spring 3.1, the `id` attribute was
+defined as an `xsd:ID` type, which constrained possible characters. As of 3.1,
+it is defined as an `xsd:string` type. Note that bean `id` uniqueness is still
+enforced by the container, though no longer by XML parsers.
+
+You are not required to supply a name or id for a bean. If no name or id is supplied
+explicitly, the container generates a unique name for that bean. However, if you want to
+refer to that bean by name, through the use of the `ref` element or
+<> style lookup, you must provide a name.
+Motivations for not supplying a name are related to using <> and <>.
+
+.Bean Naming Conventions
+****
+The convention is to use the standard Java convention for instance field names when
+naming beans. That is, bean names start with a lowercase letter, and are camel-cased
+from then on. Examples of such names would be (without quotes) `'accountManager'`,
+`'accountService'`, `'userDao'`, `'loginController'`, and so forth.
+
+Naming beans consistently makes your configuration easier to read and understand, and if
+you are using Spring AOP it helps a lot when applying advice to a set of beans related
+by name.
+****
+
+
+[[beans-beanname-alias]]
+===== Aliasing a bean outside the bean definition
+In a bean definition itself, you can supply more than one name for the bean, by using a
+combination of up to one name specified by the `id` attribute, and any number of other
+names in the `name` attribute. These names can be equivalent aliases to the same bean,
+and are useful for some situations, such as allowing each component in an application to
+refer to a common dependency by using a bean name that is specific to that component
+itself.
+
+Specifying all aliases where the bean is actually defined is not always adequate,
+however. It is sometimes desirable to introduce an alias for a bean that is defined
+elsewhere. This is commonly the case in large systems where configuration is split
+amongst each subsystem, each subsystem having its own set of object definitions. In
+XML-based configuration metadata, you can use the `` element to accomplish this.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+----
+
+In this case, a bean in the same container which is named `fromName`, may also,
+after the use of this alias definition, be referred to as `toName`.
+
+For example, the configuration metadata for subsystem A may refer to a DataSource via
+the name `subsystemA-dataSource`. The configuration metadata for subsystem B may refer to
+a DataSource via the name `subsystemB-dataSource`. When composing the main application
+that uses both these subsystems the main application refers to the DataSource via the
+name `myApp-dataSource`. To have all three names refer to the same object you add to the
+MyApp configuration metadata the following aliases definitions:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+----
+
+Now each component and the main application can refer to the dataSource through a name
+that is unique and guaranteed not to clash with any other definition (effectively
+creating a namespace), yet they refer to the same bean.
+
+.Java-configuration
+****
+If you are using Java-configuration, the `@Bean` annotation can be used to provide aliases
+see <> for details.
+****
+
+[[beans-factory-class]]
+==== Instantiating beans
+A bean definition essentially is a recipe for creating one or more objects. The
+container looks at the recipe for a named bean when asked, and uses the configuration
+metadata encapsulated by that bean definition to create (or acquire) an actual object.
+
+If you use XML-based configuration metadata, you specify the type (or class) of object
+that is to be instantiated in the `class` attribute of the `` element. This
+`class` attribute, which internally is a `Class` property on a `BeanDefinition`
+instance, is usually mandatory. (For exceptions, see
+<> and <>.)
+You use the `Class` property in one of two ways:
+
+* Typically, to specify the bean class to be constructed in the case where the container
+ itself directly creates the bean by calling its constructor reflectively, somewhat
+ equivalent to Java code using the `new` operator.
+* To specify the actual class containing the `static` factory method that will be
+ invoked to create the object, in the less common case where the container invokes a
+ `static` __factory__ method on a class to create the bean. The object type returned
+ from the invocation of the `static` factory method may be the same class or another
+ class entirely.
+
+****
+.Inner class names
+If you want to configure a bean definition for a `static` nested class, you have to use
+the __binary__ name of the inner class.
+
+For example, if you have a class called `Foo` in the `com.example` package, and this
+`Foo` class has a `static` inner class called `Bar`, the value of the `'class'`
+attribute on a bean definition would be...
+
+`com.example.Foo$Bar`
+
+Notice the use of the `$` character in the name to separate the inner class name from
+the outer class name.
+****
+
+
+[[beans-factory-class-ctor]]
+===== Instantiation with a constructor
+When you create a bean by the constructor approach, all normal classes are usable by and
+compatible with Spring. That is, the class being developed does not need to implement
+any specific interfaces or to be coded in a specific fashion. Simply specifying the bean
+class should suffice. However, depending on what type of IoC you use for that specific
+bean, you may need a default (empty) constructor.
+
+The Spring IoC container can manage virtually __any__ class you want it to manage; it is
+not limited to managing true JavaBeans. Most Spring users prefer actual JavaBeans with
+only a default (no-argument) constructor and appropriate setters and getters modeled
+after the properties in the container. You can also have more exotic non-bean-style
+classes in your container. If, for example, you need to use a legacy connection pool
+that absolutely does not adhere to the JavaBean specification, Spring can manage it as
+well.
+
+With XML-based configuration metadata you can specify your bean class as follows:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+----
+
+For details about the mechanism for supplying arguments to the constructor (if required)
+and setting object instance properties after the object is constructed, see
+<>.
+
+
+[[beans-factory-class-static-factory-method]]
+===== Instantiation with a static factory method
+When defining a bean that you create with a static factory method, you use the `class`
+attribute to specify the class containing the `static` factory method and an attribute
+named `factory-method` to specify the name of the factory method itself. You should be
+able to call this method (with optional arguments as described later) and return a live
+object, which subsequently is treated as if it had been created through a constructor.
+One use for such a bean definition is to call `static` factories in legacy code.
+
+The following bean definition specifies that the bean will be created by calling a
+factory-method. The definition does not specify the type (class) of the returned object,
+only the class containing the factory method. In this example, the `createInstance()`
+method must be a __static__ method.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+----
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class ClientService {
+ private static ClientService clientService = new ClientService();
+ private ClientService() {}
+
+ public static ClientService createInstance() {
+ return clientService;
+ }
+ }
+----
+
+For details about the mechanism for supplying (optional) arguments to the factory method
+and setting object instance properties after the object is returned from the factory,
+see <>.
+
+
+[[beans-factory-class-instance-factory-method]]
+===== Instantiation using an instance factory method
+Similar to instantiation through a <>, instantiation with an instance factory method invokes a non-static
+method of an existing bean from the container to create a new bean. To use this
+mechanism, leave the `class` attribute empty, and in the `factory-bean` attribute,
+specify the name of a bean in the current (or parent/ancestor) container that contains
+the instance method that is to be invoked to create the object. Set the name of the
+factory method itself with the `factory-method` attribute.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+----
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class DefaultServiceLocator {
+
+ private static ClientService clientService = new ClientServiceImpl();
+ private DefaultServiceLocator() {}
+
+ public ClientService createClientServiceInstance() {
+ return clientService;
+ }
+ }
+----
+
+One factory class can also hold more than one factory method as shown here:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+----
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class DefaultServiceLocator {
+
+ private static ClientService clientService = new ClientServiceImpl();
+ private static AccountService accountService = new AccountServiceImpl();
+
+ private DefaultServiceLocator() {}
+
+ public ClientService createClientServiceInstance() {
+ return clientService;
+ }
+
+ public AccountService createAccountServiceInstance() {
+ return accountService;
+ }
+
+ }
+----
+
+This approach shows that the factory bean itself can be managed and configured through
+dependency injection (DI). See <>.
+
+[NOTE]
+====
+In Spring documentation,__ factory bean__ refers to a bean that is configured in the
+Spring container that will create objects through an
+<> or
+<> factory method. By contrast,
+`FactoryBean` (notice the capitalization) refers to a Spring-specific
+<>.
+====
+
+
+
+
+[[beans-dependencies]]
+=== Dependencies
+A typical enterprise application does not consist of a single object (or bean in the
+Spring parlance). Even the simplest application has a few objects that work together to
+present what the end-user sees as a coherent application. This next section explains how
+you go from defining a number of bean definitions that stand alone to a fully realized
+application where objects collaborate to achieve a goal.
+
+
+
+[[beans-factory-collaborators]]
+==== Dependency injection
+__Dependency injection__ (DI) is a process whereby objects define their dependencies,
+that is, the other objects they work with, only through constructor arguments, arguments
+to a factory method, or properties that are set on the object instance after it is
+constructed or returned from a factory method. The container then __injects__ those
+dependencies when it creates the bean. This process is fundamentally the inverse, hence
+the name __Inversion of Control__ (IoC), of the bean itself controlling the instantiation
+or location of its dependencies on its own by using direct construction of classes, or
+the __Service Locator__ pattern.
+
+Code is cleaner with the DI principle and decoupling is more effective when objects are
+provided with their dependencies. The object does not look up its dependencies, and does
+not know the location or class of the dependencies. As such, your classes become easier
+to test, in particular when the dependencies are on interfaces or abstract base classes,
+which allow for stub or mock implementations to be used in unit tests.
+
+DI exists in two major variants, <> and <>.
+
+
+[[beans-constructor-injection]]
+===== Constructor-based dependency injection
+__Constructor-based__ DI is accomplished by the container invoking a constructor with a
+number of arguments, each representing a dependency. Calling a `static` factory method
+with specific arguments to construct the bean is nearly equivalent, and this discussion
+treats arguments to a constructor and to a `static` factory method similarly. The
+following example shows a class that can only be dependency-injected with constructor
+injection. Notice that there is nothing __special__ about this class, it is a POJO that
+has no dependencies on container specific interfaces, base classes or annotations.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class SimpleMovieLister {
+
+ // the SimpleMovieLister has a dependency on a MovieFinder
+ private MovieFinder movieFinder;
+
+ // a constructor so that the Spring container can inject a MovieFinder
+ public SimpleMovieLister(MovieFinder movieFinder) {
+ this.movieFinder = movieFinder;
+ }
+
+ // business logic that actually uses the injected MovieFinder is omitted...
+
+ }
+----
+
+[[beans-factory-ctor-arguments-resolution]]
+====== Constructor argument resolution
+Constructor argument resolution matching occurs using the argument's type. If no
+potential ambiguity exists in the constructor arguments of a bean definition, then the
+order in which the constructor arguments are defined in a bean definition is the order
+in which those arguments are supplied to the appropriate constructor when the bean is
+being instantiated. Consider the following class:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ package x.y;
+
+ public class Foo {
+
+ public Foo(Bar bar, Baz baz) {
+ // ...
+ }
+
+ }
+----
+
+No potential ambiguity exists, assuming that `Bar` and `Baz` classes are not related by
+inheritance. Thus the following configuration works fine, and you do not need to specify
+the constructor argument indexes and/or types explicitly in the ``
+element.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+
+
+----
+
+When another bean is referenced, the type is known, and matching can occur (as was the
+case with the preceding example). When a simple type is used, such as
+`true`, Spring cannot determine the type of the value, and so cannot match
+by type without help. Consider the following class:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ package examples;
+
+ public class ExampleBean {
+
+ // Number of years to calculate the Ultimate Answer
+ private int years;
+
+ // The Answer to Life, the Universe, and Everything
+ private String ultimateAnswer;
+
+ public ExampleBean(int years, String ultimateAnswer) {
+ this.years = years;
+ this.ultimateAnswer = ultimateAnswer;
+ }
+
+ }
+----
+
+.[[beans-factory-ctor-arguments-type]]Constructor argument type matching
+--
+In the preceding scenario, the container __can__ use type matching with simple types if
+you explicitly specify the type of the constructor argument using the `type` attribute.
+For example:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+----
+--
+
+.[[beans-factory-ctor-arguments-index]]Constructor argument index
+--
+Use the `index` attribute to specify explicitly the index of constructor arguments. For
+example:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+----
+
+In addition to resolving the ambiguity of multiple simple values, specifying an index
+resolves ambiguity where a constructor has two arguments of the same type. Note that the
+__index is 0 based__.
+--
+
+.[[beans-factory-ctor-arguments-name]]Constructor argument name
+--
+You can also use the constructor parameter name for value disambiguation:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+----
+
+Keep in mind that to make this work out of the box your code must be compiled with the
+debug flag enabled so that Spring can look up the parameter name from the constructor.
+If you can't compile your code with debug flag (or don't want to) you can use
+http://download.oracle.com/javase/6/docs/api/java/beans/ConstructorProperties.html[@ConstructorProperties]
+JDK annotation to explicitly name your constructor arguments. The sample class would
+then have to look as follows:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ package examples;
+
+ public class ExampleBean {
+
+ // Fields omitted
+
+ @ConstructorProperties({"years", "ultimateAnswer"})
+ public ExampleBean(int years, String ultimateAnswer) {
+ this.years = years;
+ this.ultimateAnswer = ultimateAnswer;
+ }
+
+ }
+----
+--
+
+
+[[beans-setter-injection]]
+===== Setter-based dependency injection
+__Setter-based__ DI is accomplished by the container calling setter methods on your
+beans after invoking a no-argument constructor or no-argument `static` factory method to
+instantiate your bean.
+
+The following example shows a class that can only be dependency-injected using pure
+setter injection. This class is conventional Java. It is a POJO that has no dependencies
+on container specific interfaces, base classes or annotations.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class SimpleMovieLister {
+
+ // the SimpleMovieLister has a dependency on the MovieFinder
+ private MovieFinder movieFinder;
+
+ // a setter method so that the Spring container can inject a MovieFinder
+ public void setMovieFinder(MovieFinder movieFinder) {
+ this.movieFinder = movieFinder;
+ }
+
+ // business logic that actually uses the injected MovieFinder is omitted...
+
+ }
+----
+
+The `ApplicationContext` supports constructor-based and setter-based DI for the beans it
+manages. It also supports setter-based DI after some dependencies have already been
+injected through the constructor approach. You configure the dependencies in the form of
+a `BeanDefinition`, which you use in conjunction with `PropertyEditor` instances to
+convert properties from one format to another. However, most Spring users do not work
+with these classes directly (i.e., programmatically) but rather with XML `bean`
+definitions, annotated components (i.e., classes annotated with `@Component`,
+`@Controller`, etc.), or `@Bean` methods in Java-based `@Configuration` classes. These
+sources are then converted internally into instances of `BeanDefinition` and used to
+load an entire Spring IoC container instance.
+
+.Constructor-based or setter-based DI?
+****
+Since you can mix constructor-based and setter-based DI, it is a good rule of thumb to
+use constructors for _mandatory dependencies_ and setter methods or configuration methods
+for _optional dependencies_. Note that use of the <>
+annotation on a setter method can be used to make the property a required dependency.
+
+The Spring team generally advocates constructor injection as it enables one to implement
+application components as _immutable objects_ and to ensure that required dependencies
+are not `null`. Furthermore constructor-injected components are always returned to client
+(calling) code in a fully initialized state. As a side note, a large number of constructor
+arguments is a _bad code smell_, implying that the class likely has too many
+responsibilities and should be refactored to better address proper separation of concerns.
+
+Setter injection should primarily only be used for optional dependencies that can be
+assigned reasonable default values within the class. Otherwise, not-null checks must be
+performed everywhere the code uses the dependency. One benefit of setter injection is that
+setter methods make objects of that class amenable to reconfiguration or re-injection
+later. Management through <> is therefore a compelling use case for setter
+injection.
+
+Use the DI style that makes the most sense for a particular class. Sometimes, when dealing
+with third-party classes for which you do not have the source, the choice is made for you.
+For example, if a third-party class does not expose any setter methods, then constructor
+injection may be the only available form of DI.
+****
+
+
+[[beans-dependency-resolution]]
+===== Dependency resolution process
+The container performs bean dependency resolution as follows:
+
+* The `ApplicationContext` is created and initialized with configuration metadata that
+ describes all the beans. Configuration metadata can be specified via XML, Java code, or
+ annotations.
+* For each bean, its dependencies are expressed in the form of properties, constructor
+ arguments, or arguments to the static-factory method if you are using that instead of
+ a normal constructor. These dependencies are provided to the bean, __when the bean is
+ actually created__.
+* Each property or constructor argument is an actual definition of the value to set, or
+ a reference to another bean in the container.
+* Each property or constructor argument which is a value is converted from its specified
+ format to the actual type of that property or constructor argument. By default Spring
+ can convert a value supplied in string format to all built-in types, such as `int`,
+ `long`, `String`, `boolean`, etc.
+
+The Spring container validates the configuration of each bean as the container is created.
+However, the bean properties themselves are not set until the bean __is actually created__.
+Beans that are singleton-scoped and set to be pre-instantiated (the default) are created
+when the container is created. Scopes are defined in <>. Otherwise,
+the bean is created only when it is requested. Creation of a bean potentially causes a
+graph of beans to be created, as the bean's dependencies and its dependencies'
+dependencies (and so on) are created and assigned. Note that resolution mismatches among
+those dependencies may show up late, i.e. on first creation of the affected bean.
+
+.Circular dependencies
+****
+If you use predominantly constructor injection, it is possible to create an unresolvable
+circular dependency scenario.
+
+For example: Class A requires an instance of class B through constructor injection, and
+class B requires an instance of class A through constructor injection. If you configure
+beans for classes A and B to be injected into each other, the Spring IoC container
+detects this circular reference at runtime, and throws a
+`BeanCurrentlyInCreationException`.
+
+One possible solution is to edit the source code of some classes to be configured by
+setters rather than constructors. Alternatively, avoid constructor injection and use
+setter injection only. In other words, although it is not recommended, you can configure
+circular dependencies with setter injection.
+
+Unlike the __typical__ case (with no circular dependencies), a circular dependency
+between bean A and bean B forces one of the beans to be injected into the other prior to
+being fully initialized itself (a classic chicken/egg scenario).
+****
+
+You can generally trust Spring to do the right thing. It detects configuration problems,
+such as references to non-existent beans and circular dependencies, at container
+load-time. Spring sets properties and resolves dependencies as late as possible, when
+the bean is actually created. This means that a Spring container which has loaded
+correctly can later generate an exception when you request an object if there is a
+problem creating that object or one of its dependencies. For example, the bean throws an
+exception as a result of a missing or invalid property. This potentially delayed
+visibility of some configuration issues is why `ApplicationContext` implementations by
+default pre-instantiate singleton beans. At the cost of some upfront time and memory to
+create these beans before they are actually needed, you discover configuration issues
+when the `ApplicationContext` is created, not later. You can still override this default
+behavior so that singleton beans will lazy-initialize, rather than be pre-instantiated.
+
+If no circular dependencies exist, when one or more collaborating beans are being
+injected into a dependent bean, each collaborating bean is __totally__ configured prior
+to being injected into the dependent bean. This means that if bean A has a dependency on
+bean B, the Spring IoC container completely configures bean B prior to invoking the
+setter method on bean A. In other words, the bean is instantiated (if not a
+pre-instantiated singleton), its dependencies are set, and the relevant lifecycle
+methods (such as a <>
+or the <>)
+are invoked.
+
+
+[[beans-some-examples]]
+===== Examples of dependency injection
+The following example uses XML-based configuration metadata for setter-based DI. A small
+part of a Spring XML configuration file specifies some bean definitions:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+
+
+
+
+
+----
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class ExampleBean {
+
+ private AnotherBean beanOne;
+ private YetAnotherBean beanTwo;
+ private int i;
+
+ public void setBeanOne(AnotherBean beanOne) {
+ this.beanOne = beanOne;
+ }
+
+ public void setBeanTwo(YetAnotherBean beanTwo) {
+ this.beanTwo = beanTwo;
+ }
+
+ public void setIntegerProperty(int i) {
+ this.i = i;
+ }
+
+ }
+----
+
+In the preceding example, setters are declared to match against the properties specified
+in the XML file. The following example uses constructor-based DI:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+----
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class ExampleBean {
+
+ private AnotherBean beanOne;
+ private YetAnotherBean beanTwo;
+ private int i;
+
+ public ExampleBean(
+ AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) {
+ this.beanOne = anotherBean;
+ this.beanTwo = yetAnotherBean;
+ this.i = i;
+ }
+
+ }
+----
+
+The constructor arguments specified in the bean definition will be used as arguments to
+the constructor of the `ExampleBean`.
+
+Now consider a variant of this example, where instead of using a constructor, Spring is
+told to call a `static` factory method to return an instance of the object:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+----
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class ExampleBean {
+
+ // a private constructor
+ private ExampleBean(...) {
+ ...
+ }
+
+ // a static factory method; the arguments to this method can be
+ // considered the dependencies of the bean that is returned,
+ // regardless of how those arguments are actually used.
+ public static ExampleBean createInstance (
+ AnotherBean anotherBean, YetAnotherBean yetAnotherBean, int i) {
+
+ ExampleBean eb = new ExampleBean (...);
+ // some other operations...
+ return eb;
+ }
+
+ }
+----
+
+Arguments to the `static` factory method are supplied via `` elements,
+exactly the same as if a constructor had actually been used. The type of the class being
+returned by the factory method does not have to be of the same type as the class that
+contains the `static` factory method, although in this example it is. An instance
+(non-static) factory method would be used in an essentially identical fashion (aside
+from the use of the `factory-bean` attribute instead of the `class` attribute), so
+details will not be discussed here.
+
+
+
+[[beans-factory-properties-detailed]]
+==== Dependencies and configuration in detail
+As mentioned in the previous section, you can define bean properties and constructor
+arguments as references to other managed beans (collaborators), or as values defined
+inline. Spring's XML-based configuration metadata supports sub-element types within its
+`` and `` elements for this purpose.
+
+
+[[beans-value-element]]
+===== Straight values (primitives, Strings, and so on)
+
+The `value` attribute of the `` element specifies a property or constructor
+argument as a human-readable string representation. Spring's
+<> is used to convert these
+values from a `String` to the actual type of the property or argument.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+----
+
+The following example uses the <> for even more succinct
+XML configuration.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+----
+
+The preceding XML is more succinct; however, typos are discovered at runtime rather than
+design time, unless you use an IDE such as http://www.jetbrains.com/idea/[IntelliJ
+IDEA] or the https://spring.io/tools/sts[Spring Tool Suite] (STS)
+that support automatic property completion when you create bean definitions. Such IDE
+assistance is highly recommended.
+
+You can also configure a `java.util.Properties` instance as:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+ jdbc.driver.className=com.mysql.jdbc.Driver
+ jdbc.url=jdbc:mysql://localhost:3306/mydb
+
+
+
+----
+
+The Spring container converts the text inside the `` element into a
+`java.util.Properties` instance by using the JavaBeans `PropertyEditor` mechanism. This
+is a nice shortcut, and is one of a few places where the Spring team do favor the use of
+the nested `` element over the `value` attribute style.
+
+[[beans-idref-element]]
+====== The idref element
+
+The `idref` element is simply an error-proof way to pass the __id__ (string value - not
+a reference) of another bean in the container to a `` or ``
+element.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+----
+
+The above bean definition snippet is __exactly__ equivalent (at runtime) to the
+following snippet:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+----
+
+The first form is preferable to the second, because using the `idref` tag allows the
+container to validate __at deployment time__ that the referenced, named bean actually
+exists. In the second variation, no validation is performed on the value that is passed
+to the `targetName` property of the `client` bean. Typos are only discovered (with most
+likely fatal results) when the `client` bean is actually instantiated. If the `client`
+bean is a <> bean, this typo and the resulting exception
+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 `` element
+brings value is in the configuration of <> in a
+`ProxyFactoryBean` bean definition. Using `` elements when you specify the
+interceptor names prevents you from misspelling an interceptor id.
+
+
+[[beans-ref-element]]
+===== References to other beans (collaborators)
+The `ref` element is the final element inside a `` or ``
+definition element. Here you set the value of the specified property of a bean to be a
+reference to another bean (a collaborator) managed by the container. The referenced bean
+is a dependency of the bean whose property will be set, and it is initialized on demand
+as needed before the property is set. (If the collaborator is a singleton bean, it may
+be initialized already by the container.) All references are ultimately a reference to
+another object. Scoping and validation depend on whether you specify the id/name of the
+other object through the `bean`, `local,` or `parent` attributes.
+
+Specifying the target bean through the `bean` attribute of the `` tag is the most
+general form, and allows creation of a reference to any bean in the same container or
+parent container, regardless of whether it is in the same XML file. The value of the
+`bean` attribute may be the same as the `id` attribute of the target bean, or as one of
+the values in the `name` attribute of the target bean.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+----
+
+Specifying the target bean through the `parent` attribute creates a reference to a bean
+that is in a parent container of the current container. The value of the `parent`
+attribute may be the same as either the `id` attribute of the target bean, or one of the
+values in the `name` attribute of the target bean, and the target bean must be in a
+parent container of the current one. You use this bean reference variant mainly when you
+have a hierarchy of containers and you want to wrap an existing bean in a parent
+container with a proxy that will have the same name as the parent bean.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+----
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+ class="org.springframework.aop.framework.ProxyFactoryBean">
+
+
+
+
+
+----
+
+[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]]
+===== Inner beans
+A `` element inside the `` or `` elements defines a
+so-called __inner bean__.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+
+----
+
+An inner bean definition does not require a defined id or name; the container ignores
+these values. It also ignores the `scope` flag. Inner beans are __always__ anonymous and
+they are __always__ created with the outer bean. It is __not__ possible to inject inner
+beans into collaborating beans other than into the enclosing bean.
+
+
+[[beans-collection-elements]]
+===== Collections
+In the `
`, ``, ``, and `` elements, you set the properties
+and arguments of the Java `Collection` types `List`, `Set`, `Map`, and `Properties`,
+respectively.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+ administrator@example.org
+ support@example.org
+ development@example.org
+
+
+
+
+
+ a list element followed by a reference
+
+
+
+
+
+
+
+
+
+
+ just some string
+
+
+
+
+----
+
+__The value of a map key or value, or a set value, can also again be any of the
+following elements:__
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+ bean | ref | idref | list | set | map | props | value | null
+----
+
+[[beans-collection-elements-merging]]
+====== Collection merging
+The Spring container also supports the __merging__ of collections. An application
+developer can define a parent-style `
`, ``, `` or `` element,
+and have child-style `
`, ``, `` or `` elements inherit and
+override values from the parent collection. That is, the child collection's values are
+the result of merging the elements of the parent and child collections, with the child's
+collection elements overriding values specified in the parent collection.
+
+__This section on merging discusses the parent-child bean mechanism. Readers unfamiliar
+with parent and child bean definitions may wish to read the
+<> before continuing.__
+
+The following example demonstrates collection merging:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+ administrator@example.com
+ support@example.com
+
+
+
+
+
+
+
+ sales@example.com
+ support@example.co.uk
+
+
+
+
+----
+
+Notice the use of the `merge=true` attribute on the `` element of the
+`adminEmails` property of the `child` bean definition. When the `child` bean is resolved
+and instantiated by the container, the resulting instance has an `adminEmails`
+`Properties` collection that contains the result of the merging of the child's
+`adminEmails` collection with the parent's `adminEmails` collection.
+
+[literal]
+[subs="verbatim,quotes"]
+----
+administrator=administrator@example.com
+sales=sales@example.com
+support=support@example.co.uk
+----
+
+The child `Properties` collection's value set inherits all property elements from the
+parent ``, and the child's value for the `support` value overrides the value in
+the parent collection.
+
+This merging behavior applies similarly to the `
`, ``, and ``
+collection types. In the specific case of the `
` element, the semantics
+associated with the `List` collection type, that is, the notion of an `ordered`
+collection of values, is maintained; the parent's values precede all of the child list's
+values. In the case of the `Map`, `Set`, and `Properties` collection types, no ordering
+exists. Hence no ordering semantics are in effect for the collection types that underlie
+the associated `Map`, `Set`, and `Properties` implementation types that the container
+uses internally.
+
+[[beans-collection-merge-limitations]]
+====== Limitations of collection merging
+You cannot merge different collection types (such as a `Map` and a `List`), and if you
+do attempt to do so an appropriate `Exception` is thrown. The `merge` attribute must be
+specified on the lower, inherited, child definition; specifying the `merge` attribute on
+a parent collection definition is redundant and will not result in the desired merging.
+
+[[beans-collection-elements-strongly-typed]]
+====== Strongly-typed collection
+With the introduction of generic types in Java 5, you can use strongly typed collections.
+That is, it is possible to declare a `Collection` type such that it can only contain
+`String` elements (for example). If you are using Spring to dependency-inject a
+strongly-typed `Collection` into a bean, you can take advantage of Spring's
+type-conversion support such that the elements of your strongly-typed `Collection`
+instances are converted to the appropriate type prior to being added to the `Collection`.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class Foo {
+
+ private Map accounts;
+
+ public void setAccounts(Map accounts) {
+ this.accounts = accounts;
+ }
+ }
+----
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+----
+
+When the `accounts` property of the `foo` bean is prepared for injection, the generics
+information about the element type of the strongly-typed `Map` is
+available by reflection. Thus Spring's type conversion infrastructure recognizes the
+various value elements as being of type `Float`, and the string values `9.99, 2.75`, and
+`3.99` are converted into an actual `Float` type.
+
+
+[[beans-null-element]]
+===== Null and empty string values
+Spring treats empty arguments for properties and the like as empty `Strings`. The
+following XML-based configuration metadata snippet sets the email property to the empty
+`String` value ("").
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+----
+
+The preceding example is equivalent to the following Java code:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ exampleBean.setEmail("")
+----
+
+The `` element handles `null` values. For example:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+----
+
+The above configuration is equivalent to the following Java code:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ exampleBean.setEmail(null)
+----
+
+
+[[beans-p-namespace]]
+===== XML shortcut with the p-namespace
+The p-namespace enables you to use the `bean` element's attributes, instead of nested
+`` elements, to describe your property values and/or collaborating beans.
+
+Spring supports extensible configuration formats <>, which are
+based on an XML Schema definition. The `beans` configuration format discussed in this
+chapter is defined in an XML Schema document. However, the p-namespace is not defined in
+an XSD file and exists only in the core of Spring.
+
+The following example shows two XML snippets that resolve to the same result: The first
+uses standard XML format and the second uses the p-namespace.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+----
+
+The example shows an attribute in the p-namespace called email in the bean definition.
+This tells Spring to include a property declaration. As previously mentioned, the
+p-namespace does not have a schema definition, so you can set the name of the attribute
+to the property name.
+
+This next example includes two more bean definitions that both have a reference to
+another bean:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+
+
+
+
+
+----
+
+As you can see, this example includes not only a property value using the p-namespace,
+but also uses a special format to declare property references. Whereas the first bean
+definition uses `` to create a reference from bean
+`john` to bean `jane`, the second bean definition uses `p:spouse-ref="jane"` as an
+attribute to do the exact same thing. In this case `spouse` is the property name,
+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]]
+===== XML shortcut with the c-namespace
+Similar to the <>, the __c-namespace__, newly introduced in Spring
+3.1, allows usage of inlined attributes for configuring the constructor arguments rather
+then nested `constructor-arg` elements.
+
+Let's review the examples from <> with the `c:` namespace:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+----
+
+The `c:` namespace uses the same conventions as the `p:` one (trailing `-ref` for bean
+references) for setting the constructor arguments by their names. And just as well, it
+needs to be declared even though it is not defined in an XSD schema (but it exists
+inside the Spring core).
+
+For the rare cases where the constructor argument names are not available (usually if
+the bytecode was compiled without debugging information), one can use fallback to the
+argument indexes:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+----
+
+[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
+<> is quite efficient in matching
+arguments so unless one really needs to, we recommend using the name notation
+through-out your configuration.
+
+
+[[beans-compound-property-names]]
+===== Compound property names
+You can use compound or nested property names when you set bean properties, as long as
+all components of the path except the final property name are not `null`. Consider the
+following bean definition.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+----
+
+The `foo` bean has a `fred` property, which has a `bob` property, which has a `sammy`
+property, and that final `sammy` property is being set to the value `123`. In order for
+this to work, the `fred` property of `foo`, and the `bob` property of `fred` must not be
+`null` after the bean is constructed, or a `NullPointerException` is thrown.
+
+
+
+[[beans-factory-dependson]]
+==== Using depends-on
+
+If a bean is a dependency of another that usually means that one bean is set as a
+property of another. Typically you accomplish this with the <`
+element>> in XML-based configuration metadata. However, sometimes dependencies between
+beans are less direct; for example, a static initializer in a class needs to be
+triggered, such as database driver registration. The `depends-on` attribute can
+explicitly force one or more beans to be initialized before the bean using this element
+is initialized. The following example uses the `depends-on` attribute to express a
+dependency on a single bean:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+----
+
+To express a dependency on multiple beans, supply a list of bean names as the value of
+the `depends-on` attribute, with commas, whitespace and semicolons, used as valid
+delimiters:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+----
+
+[NOTE]
+====
+The `depends-on` attribute in the bean definition can specify both an initialization
+time dependency and, in the case of <> 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.
+====
+
+
+
+[[beans-factory-lazy-init]]
+==== Lazy-initialized beans
+By default, `ApplicationContext` implementations eagerly create and configure all
+<> beans as part of the initialization
+process. Generally, this pre-instantiation is desirable, because errors in the
+configuration or surrounding environment are discovered immediately, as opposed to hours
+or even days later. When this behavior is __not__ desirable, you can prevent
+pre-instantiation of a singleton bean by marking the bean definition as
+lazy-initialized. A lazy-initialized bean tells the IoC container to create a bean
+instance when it is first requested, rather than at startup.
+
+In XML, this behavior is controlled by the `lazy-init` attribute on the ``
+element; for example:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+----
+
+When the preceding configuration is consumed by an `ApplicationContext`, the bean named
+`lazy` is not eagerly pre-instantiated when the `ApplicationContext` is starting up,
+whereas the `not.lazy` bean is eagerly pre-instantiated.
+
+However, when a lazy-initialized bean is a dependency of a singleton bean that is
+__not__ lazy-initialized, the `ApplicationContext` creates the lazy-initialized bean at
+startup, because it must satisfy the singleton's dependencies. The lazy-initialized bean
+is injected into a singleton bean elsewhere that is not lazy-initialized.
+
+You can also control lazy-initialization at the container level by using the
+`default-lazy-init` attribute on the `` element; for example:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+----
+
+
+
+[[beans-factory-autowire]]
+==== Autowiring collaborators
+The Spring container can __autowire__ relationships between collaborating beans. You can
+allow Spring to resolve collaborators (other beans) automatically for your bean by
+inspecting the contents of the `ApplicationContext`. Autowiring has the following
+advantages:
+
+* Autowiring can significantly reduce the need to specify properties or constructor
+ arguments. (Other mechanisms such as a bean template
+ <> are also valuable
+ in this regard.)
+* Autowiring can update a configuration as your objects evolve. For example, if you need
+ to add a dependency to a class, that dependency can be satisfied automatically without
+ you needing to modify the configuration. Thus autowiring can be especially useful
+ during development, without negating the option of switching to explicit wiring when
+ the code base becomes more stable.
+
+When using XML-based configuration metadata footnote:[See
+pass:specialcharacters,macros[<>]], you specify autowire
+mode for a bean definition with the `autowire` attribute of the `` element. The
+autowiring functionality has five modes. You specify autowiring __per__ bean and thus
+can choose which ones to autowire.
+
+[[beans-factory-autowiring-modes-tbl]]
+.Autowiring modes
+|===
+| Mode| Explanation
+
+| no
+| (Default) No autowiring. Bean references must be defined via a `ref` element. Changing
+ the default setting is not recommended for larger deployments, because specifying
+ collaborators explicitly gives greater control and clarity. To some extent, it
+ documents the structure of a system.
+
+| byName
+| Autowiring by property name. Spring looks for a bean with the same name as the
+ property that needs to be autowired. For example, if a bean definition is set to
+ autowire by name, and it contains a __master__ property (that is, it has a
+ __setMaster(..)__ method), Spring looks for a bean definition named `master`, and uses
+ it to set the property.
+
+| byType
+| Allows a property to be autowired if exactly one bean of the property type exists in
+ the container. If more than one exists, a fatal exception is thrown, which indicates
+ that you may not use __byType__ autowiring for that bean. If there are no matching
+ beans, nothing happens; the property is not set.
+
+| constructor
+| Analogous to __byType__, but applies to constructor arguments. If there is not exactly
+ one bean of the constructor argument type in the container, a fatal error is raised.
+|===
+
+With __byType__ or __constructor__ autowiring mode, you can wire arrays and
+typed-collections. In such cases __all__ autowire candidates within the container that
+match the expected type are provided to satisfy the dependency. You can autowire
+strongly-typed Maps if the expected key type is `String`. An autowired Maps values will
+consist of all bean instances that match the expected type, and the Maps keys will
+contain the corresponding bean names.
+
+You can combine autowire behavior with dependency checking, which is performed after
+autowiring completes.
+
+
+[[beans-autowired-exceptions]]
+===== Limitations and disadvantages of autowiring
+Autowiring works best when it is used consistently across a project. If autowiring is
+not used in general, it might be confusing to developers to use it to wire only one or
+two bean definitions.
+
+Consider the limitations and disadvantages of autowiring:
+
+* Explicit dependencies in `property` and `constructor-arg` settings always override
+ autowiring. You cannot autowire so-called __simple__ properties such as primitives,
+ `Strings`, and `Classes` (and arrays of such simple properties). This limitation is
+ by-design.
+* Autowiring is less exact than explicit wiring. Although, as noted in the above table,
+ Spring is careful to avoid guessing in case of ambiguity that might have unexpected
+ results, the relationships between your Spring-managed objects are no longer
+ documented explicitly.
+* Wiring information may not be available to tools that may generate documentation from
+ a Spring container.
+* Multiple bean definitions within the container may match the type specified by the
+ setter method or constructor argument to be autowired. For arrays, collections, or
+ Maps, this is not necessarily a problem. However for dependencies that expect a single
+ value, this ambiguity is not arbitrarily resolved. If no unique bean definition is
+ available, an exception is thrown.
+
+In the latter scenario, you have several options:
+
+* Abandon autowiring in favor of explicit wiring.
+* Avoid autowiring for a bean definition by setting its `autowire-candidate` attributes
+ to `false` as described in the next section.
+* Designate a single bean definition as the __primary__ candidate by setting the
+ `primary` attribute of its `` element to `true`.
+* Implement the more fine-grained control available
+ with annotation-based configuration, as described in <>.
+
+
+[[beans-factory-autowire-candidate]]
+===== Excluding a bean from autowiring
+On a per-bean basis, you can exclude a bean from autowiring. In Spring's XML format, set
+the `autowire-candidate` attribute of the `` element to `false`; the container
+makes that specific bean definition unavailable to the autowiring infrastructure
+(including annotation style configurations such as <>).
+
+You can also limit autowire candidates based on pattern-matching against bean names. The
+top-level `` element accepts one or more patterns within its
+`default-autowire-candidates` attribute. For example, to limit autowire candidate status
+to any bean whose name ends with __Repository,__ provide a value of *Repository. To
+provide multiple patterns, define them in a comma-separated list. An explicit value of
+`true` or `false` for a bean definitions `autowire-candidate` attribute always takes
+precedence, and for such beans, the pattern matching rules do not apply.
+
+These techniques are useful for beans that you never want to be injected into other
+beans by autowiring. It does not mean that an excluded bean cannot itself be configured
+using autowiring. Rather, the bean itself is not a candidate for autowiring other beans.
+
+
+
+[[beans-factory-method-injection]]
+==== Method injection
+In most application scenarios, most beans in the container are
+<>. When a singleton bean needs to
+collaborate with another singleton bean, or a non-singleton bean needs to collaborate
+with another non-singleton bean, you typically handle the dependency by defining one
+bean as a property of the other. A problem arises when the bean lifecycles are
+different. Suppose singleton bean A needs to use non-singleton (prototype) bean B,
+perhaps on each method invocation on A. The container only creates the singleton bean A
+once, and thus only gets one opportunity to set the properties. The container cannot
+provide bean A with a new instance of bean B every time one is needed.
+
+A solution is to forego some inversion of control. You can <> by implementing the `ApplicationContextAware` interface,
+and by <> ask for (a
+typically new) bean B instance every time bean A needs it. The following is an example
+of this approach:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ // a class that uses a stateful Command-style class to perform some processing
+ package fiona.apple;
+
+ // Spring-API imports
+ import org.springframework.beans.BeansException;
+ import org.springframework.context.ApplicationContext;
+ import org.springframework.context.ApplicationContextAware;
+
+ public class CommandManager implements ApplicationContextAware {
+
+ private ApplicationContext applicationContext;
+
+ public Object process(Map commandState) {
+ // grab a new instance of the appropriate Command
+ Command command = createCommand();
+ // set the state on the (hopefully brand new) Command instance
+ command.setState(commandState);
+ return command.execute();
+ }
+
+ protected Command createCommand() {
+ // notice the Spring API dependency!
+ return this.applicationContext.getBean("command", Command.class);
+ }
+
+ public void setApplicationContext(
+ ApplicationContext applicationContext) throws BeansException {
+ this.applicationContext = applicationContext;
+ }
+ }
+----
+
+The preceding is not desirable, because the business code is aware of and coupled to the
+Spring Framework. Method Injection, a somewhat advanced feature of the Spring IoC
+container, allows this use case to be handled in a clean fashion.
+
+****
+You can read more about the motivation for Method Injection in
+https://spring.io/blog/2004/08/06/method-injection/[this blog entry].
+****
+
+
+[[beans-factory-lookup-method-injection]]
+===== Lookup method injection
+Lookup method injection is the ability of the container to override methods on
+__container managed beans__, to return the lookup result for another named bean in the
+container. The lookup typically involves a prototype bean as in the scenario described
+in the preceding section. The Spring Framework implements this method injection by using
+bytecode generation from the CGLIB library to generate dynamically a subclass that
+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
+yourself and to supply a stub implementation of the `abstract` method. Finally, objects
+that have been the target of method injection cannot be serialized. As of Spring 3.2 it
+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()`
+method. Your `CommandManager` class will not have any Spring dependencies, as can be
+seen in the reworked example:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ package fiona.apple;
+
+ // no more Spring imports!
+
+ public abstract class CommandManager {
+
+ public Object process(Object commandState) {
+ // grab a new instance of the appropriate Command interface
+ Command command = createCommand();
+ // set the state on the (hopefully brand new) Command instance
+ command.setState(commandState);
+ return command.execute();
+ }
+
+ // okay... but where is the implementation of this method?
+ protected abstract Command createCommand();
+ }
+----
+
+In the client class containing the method to be injected (the `CommandManager` in this
+case), the method to be injected requires a signature of the following form:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+ [abstract] theMethodName(no-arguments);
+----
+
+If the method is `abstract`, the dynamically-generated subclass implements the method.
+Otherwise, the dynamically-generated subclass overrides the concrete method defined in
+the original class. For example:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+
+----
+
+The bean identified as __commandManager__ calls its own method `createCommand()`
+whenever it needs a new instance of the __command__ bean. You must be careful to deploy
+the `command` bean as a prototype, if that is actually what is needed. If it is deployed
+as a <>, the same instance of the `command`
+bean is returned each time.
+
+[TIP]
+====
+The interested reader may also find the `ServiceLocatorFactoryBean` (in the
+`org.springframework.beans.factory.config` package) to be of use. The approach used in
+ServiceLocatorFactoryBean is similar to that of another utility class,
+`ObjectFactoryCreatingFactoryBean`, but it allows you to specify your own lookup
+interface as opposed to a Spring-specific lookup interface. Consult the javadocs of
+these classes for additional information.
+====
+
+
+[[beans-factory-arbitrary-method-replacement]]
+===== Arbitrary method replacement
+A less useful form of method injection than lookup method Injection is the ability to
+replace arbitrary methods in a managed bean with another method implementation. Users
+may safely skip the rest of this section until the functionality is actually needed.
+
+With XML-based configuration metadata, you can use the `replaced-method` element to
+replace an existing method implementation with another, for a deployed bean. Consider
+the following class, with a method computeValue, which we want to override:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class MyValueCalculator {
+
+ public String computeValue(String input) {
+ // some real code...
+ }
+
+ // some other methods...
+
+ }
+----
+
+A class implementing the `org.springframework.beans.factory.support.MethodReplacer`
+interface provides the new method definition.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ /**
+ * meant to be used to override the existing computeValue(String)
+ * implementation in MyValueCalculator
+ */
+ public class ReplacementComputeValue implements MethodReplacer {
+
+ public Object reimplement(Object o, Method m, Object[] args) throws Throwable {
+ // get the input value, work with it, and return a computed result
+ String input = (String) args[0];
+ ...
+ return ...;
+ }
+ }
+----
+
+The bean definition to deploy the original class and specify the method override would
+look like this:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+ String
+
+
+
+
+----
+
+You can use one or more contained `` elements within the ``
+element to indicate the method signature of the method being overridden. The signature
+for the arguments is necessary only if the method is overloaded and multiple variants
+exist within the class. For convenience, the type string for an argument may be a
+substring of the fully qualified type name. For example, the following all match
+`java.lang.String`:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ java.lang.String
+ String
+ Str
+----
+
+Because the number of arguments is often enough to distinguish between each possible
+choice, this shortcut can save a lot of typing, by allowing you to type only the
+shortest string that will match an argument type.
+
+
+
+
+[[beans-factory-scopes]]
+=== Bean scopes
+When you create a bean definition, you create a __recipe__ for creating actual instances
+of the class defined by that bean definition. The idea that a bean definition is a
+recipe is important, because it means that, as with a class, you can create many object
+instances from a single recipe.
+
+You can control not only the various dependencies and configuration values that are to
+be plugged into an object that is created from a particular bean definition, but also
+the __scope__ of the objects created from a particular bean definition. This approach is
+powerful and flexible in that you can __choose__ the scope of the objects you create
+through configuration instead of having to bake in the scope of an object at the Java
+class level. Beans can be defined to be deployed in one of a number of scopes: out of
+the box, the Spring Framework supports five scopes, three of which are available only if
+you use a web-aware `ApplicationContext`.
+
+The following scopes are supported out of the box. You can also create
+<>
+
+[[beans-factory-scopes-tbl]]
+.Bean scopes
+|===
+| Scope| Description
+
+| <>
+| (Default) Scopes a single bean definition to a single object instance per Spring IoC
+ container.
+
+| <>
+| Scopes a single bean definition to any number of object instances.
+
+| <>
+| Scopes a single bean definition to the lifecycle of a single HTTP request; that is,
+ each HTTP request has its own instance of a bean created off the back of a single bean
+ definition. Only valid in the context of a web-aware Spring `ApplicationContext`.
+
+| <>
+| Scopes a single bean definition to the lifecycle of an HTTP `Session`. Only valid in
+ the context of a web-aware Spring `ApplicationContext`.
+
+| <>
+| Scopes a single bean definition to the lifecycle of a global HTTP `Session`. Typically
+ only valid when used in a portlet context. Only valid in the context of a web-aware
+ Spring `ApplicationContext`.
+
+| <>
+| Scopes a single bean definition to the lifecycle of a `ServletContext`. Only valid in
+ the context of a web-aware Spring `ApplicationContext`.
+|===
+
+[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-singleton]]
+==== The singleton scope
+Only one __shared__ instance of a singleton bean is managed, and all requests for beans
+with an id or ids matching that bean definition result in that one specific bean
+instance being returned by the Spring container.
+
+To put it another way, when you define a bean definition and it is scoped as a
+singleton, the Spring IoC container creates __exactly one__ instance of the object
+defined by that bean definition. This single instance is stored in a cache of such
+singleton beans, and __all subsequent requests and references__ for that named bean
+return the cached object.
+
+image::images/singleton.png[width=400]
+
+Spring's concept of a singleton bean differs from the Singleton pattern as defined in
+the Gang of Four (GoF) patterns book. The GoF Singleton hard-codes the scope of an
+object such that one __and only one__ instance of a particular class is created __per
+ClassLoader__. The scope of the Spring singleton is best described as __per container
+and per bean__. This means that if you define one bean for a particular class in a
+single Spring container, then the Spring container creates one __and only one__ instance
+of the class defined by that bean definition. __The singleton scope is the default scope
+in Spring__. To define a bean as a singleton in XML, you would write, for example:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+----
+
+
+
+[[beans-factory-scopes-prototype]]
+==== The prototype scope
+The non-singleton, prototype scope of bean deployment results in the __creation of a new
+bean instance__ every time a request for that specific bean is made. That is, the bean
+is injected into another bean or you request it through a `getBean()` method call on the
+container. As a rule, use the prototype scope for all stateful beans and the singleton
+scope for stateless beans.
+
+The following diagram illustrates the Spring prototype scope. __A data access object
+(DAO) is not typically configured as a prototype, because a typical DAO does not hold
+any conversational state; it was just easier for this author to reuse the core of the
+singleton diagram.__
+
+image::images/prototype.png[width=400]
+
+The following example defines a bean as a prototype in XML:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+----
+
+In contrast to the other scopes, Spring does not manage the complete lifecycle of a
+prototype bean: the container instantiates, configures, and otherwise assembles a
+prototype object, and hands it to the client, with no further record of that prototype
+instance. Thus, although__ initialization__ lifecycle callback methods are called on all
+objects regardless of scope, in the case of prototypes, configured __destruction__
+lifecycle callbacks are __not__ called. The client code must clean up prototype-scoped
+objects and release expensive resources that the prototype bean(s) are holding. To get
+the Spring container to release resources held by prototype-scoped beans, try using a
+custom <>, which holds a reference to
+beans that need to be cleaned up.
+
+In some respects, the Spring container's role in regard to a prototype-scoped bean is a
+replacement for the Java `new` operator. All lifecycle management past that point must
+be handled by the client. (For details on the lifecycle of a bean in the Spring
+container, see <>.)
+
+
+
+[[beans-factory-scopes-sing-prot-interaction]]
+==== Singleton beans with prototype-bean dependencies
+When you use singleton-scoped beans with dependencies on prototype beans, be aware that
+__dependencies are resolved at instantiation time__. Thus if you dependency-inject a
+prototype-scoped bean into a singleton-scoped bean, a new prototype bean is instantiated
+and then dependency-injected into the singleton bean. The prototype instance is the sole
+instance that is ever supplied to the singleton-scoped bean.
+
+However, suppose you want the singleton-scoped bean to acquire a new instance of the
+prototype-scoped bean repeatedly at runtime. You cannot dependency-inject a
+prototype-scoped bean into your singleton bean, because that injection occurs only
+__once__, when the Spring container is instantiating the singleton bean and resolving
+and injecting its dependencies. If you need a new instance of a prototype bean at
+runtime more than once, see <>
+
+
+
+[[beans-factory-scopes-other]]
+==== Request, session, and global session scopes
+The `request`, `session`, and `global session` scopes are __only__ available if you use
+a web-aware Spring `ApplicationContext` implementation (such as
+`XmlWebApplicationContext`). If you use these scopes with regular Spring IoC containers
+such as the `ClassPathXmlApplicationContext`, you get an `IllegalStateException`
+complaining about an unknown bean scope.
+
+
+[[beans-factory-scopes-other-web-configuration]]
+===== Initial web configuration
+To support the scoping of beans at the `request`, `session`, and `global session` levels
+(web-scoped beans), some minor initial configuration is required before you define your
+beans. (This initial setup is __not__ required for the standard scopes, singleton and
+prototype.)
+
+How you accomplish this initial setup depends on your particular Servlet environment..
+
+If you access scoped beans within Spring Web MVC, in effect, within a request that is
+processed by the Spring `DispatcherServlet`, or `DispatcherPortlet`, then no special
+setup is necessary: `DispatcherServlet` and `DispatcherPortlet` already expose all
+relevant state.
+
+If you use a Servlet 2.5 web container, with requests processed outside of Spring's
+DispatcherServlet (for example, when using JSF or Struts), you need to register the
+`org.springframework.web.context.request.RequestContextListener` `ServletRequestListener`.
+For Servlet 3.0+, this can done programmatically via the `WebApplicationInitializer`
+interface. Alternatively, or for older containers, add the following declaration to
+your web application's `web.xml` file:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+ ...
+
+
+ org.springframework.web.context.request.RequestContextListener
+
+
+ ...
+
+----
+
+Alternatively, if there are issues with your listener setup, consider the provided
+`RequestContextFilter`. The filter mapping depends on the surrounding web
+application configuration, so you have to change it as appropriate.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+ ...
+
+ requestContextFilter
+ org.springframework.web.filter.RequestContextFilter
+
+
+ requestContextFilter
+ /*
+
+ ...
+
+----
+
+`DispatcherServlet`, `RequestContextListener` and `RequestContextFilter` all do exactly
+the same thing, namely bind the HTTP request object to the `Thread` that is servicing
+that request. This makes beans that are request- and session-scoped available further
+down the call chain.
+
+
+[[beans-factory-scopes-request]]
+===== Request scope
+Consider the following bean definition:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+----
+
+The Spring container creates a new instance of the `LoginAction` bean by using the
+`loginAction` bean definition for each and every HTTP request. That is, the
+`loginAction` bean is scoped at the HTTP request level. You can change the internal
+state of the instance that is created as much as you want, because other instances
+created from the same `loginAction` bean definition will not see these changes in state;
+they are particular to an individual request. When the request completes processing, the
+bean that is scoped to the request is discarded.
+
+
+[[beans-factory-scopes-session]]
+===== Session scope
+Consider the following bean definition:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+----
+
+The Spring container creates a new instance of the `UserPreferences` bean by using the
+`userPreferences` bean definition for the lifetime of a single HTTP `Session`. In other
+words, the `userPreferences` bean is effectively scoped at the HTTP `Session` level. As
+with `request-scoped` beans, you can change the internal state of the instance that is
+created as much as you want, knowing that other HTTP `Session` instances that are also
+using instances created from the same `userPreferences` bean definition do not see these
+changes in state, because they are particular to an individual HTTP `Session`. When the
+HTTP `Session` is eventually discarded, the bean that is scoped to that particular HTTP
+`Session` is also discarded.
+
+
+[[beans-factory-scopes-global-session]]
+===== Global session scope
+Consider the following bean definition:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+----
+
+The `global session` scope is similar to the standard HTTP `Session` scope
+(<>), and applies only in the context of
+portlet-based web applications. The portlet specification defines the notion of a global
+`Session` that is shared among all portlets that make up a single portlet web
+application. Beans defined at the `global session` scope are scoped (or bound) to the
+lifetime of the global portlet `Session`.
+
+If you write a standard Servlet-based web application and you define one or more beans
+as having `global session` scope, the standard HTTP `Session` scope is used, and no
+error is raised.
+
+
+[[beans-factory-scopes-application]]
+===== Application scope
+Consider the following bean definition:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+----
+
+The Spring container creates a new instance of the `AppPreferences` bean by using the
+`appPreferences` bean definition once for the entire web application. That is, the
+`appPreferences` bean is scoped at the `ServletContext` level, stored as a regular
+`ServletContext` attribute. This is somewhat similar to a Spring singleton bean but
+differs in two important ways: It is a singleton per `ServletContext`, not per Spring
+'ApplicationContext' (or which there may be several in any given web application),
+and it is actually exposed and therefore visible as a `ServletContext` attribute.
+
+
+[[beans-factory-scopes-other-injection]]
+===== Scoped beans as dependencies
+The Spring IoC container manages not only the instantiation of your objects (beans), but
+also the wiring up of collaborators (or dependencies). If you want to inject (for
+example) an HTTP request scoped bean into another bean, you must inject an AOP proxy in
+place of the scoped bean. That is, you need to inject a proxy object that exposes the
+same public interface as the scoped object but that can also retrieve the real, target
+object from the relevant scope (for example, an HTTP request) and delegate method calls
+onto the real object.
+
+[NOTE]
+====
+You __do not__ need to use the `` 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.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+----
+
+To create such a proxy, you insert a child `` element into a scoped
+bean definition. See <> and
+<>.) Why do definitions of beans scoped at the `request`, `session`,
+`globalSession` and custom-scope levels require the `` element ?
+Let's examine the following singleton bean definition and contrast it with what you need
+to define for the aforementioned scopes. (The following `userPreferences` bean
+definition as it stands is __incomplete.)__
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+----
+
+In the preceding example, the singleton bean `userManager` is injected with a reference
+to the HTTP `Session`-scoped bean `userPreferences`. The salient point here is that the
+`userManager` bean is a singleton: it will be instantiated __exactly once__ per
+container, and its dependencies (in this case only one, the `userPreferences` bean) are
+also injected only once. This means that the `userManager` bean will only operate on the
+exact same `userPreferences` object, that is, the one that it was originally injected
+with.
+
+This is __not__ the behavior you want when injecting a shorter-lived scoped bean into a
+longer-lived scoped bean, for example injecting an HTTP `Session`-scoped collaborating
+bean as a dependency into singleton bean. Rather, you need a single `userManager`
+object, and for the lifetime of an HTTP `Session`, you need a `userPreferences` object
+that is specific to said HTTP `Session`. Thus the container creates an object that
+exposes the exact same public interface as the `UserPreferences` class (ideally an
+object that __is a__ `UserPreferences` instance) which can fetch the real
+`UserPreferences` object from the scoping mechanism (HTTP request, `Session`, etc.). The
+container injects this proxy object into the `userManager` bean, which is unaware that
+this `UserPreferences` reference is a proxy. In this example, when a `UserManager`
+instance invokes a method on the dependency-injected `UserPreferences` object, it
+actually is invoking a method on the proxy. The proxy then fetches the real
+`UserPreferences` object from (in this case) the HTTP `Session`, and delegates the
+method invocation onto the retrieved real `UserPreferences` object.
+
+Thus you need the following, correct and complete, configuration when injecting
+`request-`, `session-`, and `globalSession-scoped` beans into collaborating objects:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+----
+
+[[beans-factory-scopes-other-injection-proxies]]
+====== Choosing the type of proxy to create
+By default, when the Spring container creates a proxy for a bean that is marked up with
+the `` 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
+the `proxy-target-class` attribute of the `` element. Using JDK
+interface-based proxies means that you do not need additional libraries in your
+application classpath to effect such proxying. However, it also means that the class of
+the scoped bean must implement at least one interface, and __that all__ collaborators
+into which the scoped bean is injected must reference the bean through one of its
+interfaces.
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+----
+
+For more detailed information about choosing class-based or interface-based proxying,
+see <>.
+
+
+
+[[beans-factory-scopes-custom]]
+==== Custom scopes
+The bean scoping mechanism is extensible; You can define your own
+scopes, or even redefine existing scopes, although the latter is considered bad practice
+and you __cannot__ override the built-in `singleton` and `prototype` scopes.
+
+
+[[beans-factory-scopes-custom-creating]]
+===== Creating a custom scope
+To integrate your custom scope(s) into the Spring container, you need to implement the
+`org.springframework.beans.factory.config.Scope` interface, which is described in this
+section. For an idea of how to implement your own scopes, see the `Scope`
+implementations that are supplied with the Spring Framework itself and the
+{javadoc-baseurl}/org/springframework/beans/factory/config/Scope.html[`Scope` javadocs],
+which explains the methods you need to implement in more detail.
+
+The `Scope` interface has four methods to get objects from the scope, remove them from
+the scope, and allow them to be destroyed.
+
+The following method returns the object from the underlying scope. The session scope
+implementation, for example, returns the session-scoped bean (and if it does not exist,
+the method returns a new instance of the bean, after having bound it to the session for
+future reference).
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ Object get(String name, ObjectFactory objectFactory)
+----
+
+The following method removes the object from the underlying scope. The session scope
+implementation for example, removes the session-scoped bean from the underlying session.
+The object should be returned, but you can return null if the object with the specified
+name is not found.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ Object remove(String name)
+----
+
+The following method registers the callbacks the scope should execute when it is
+destroyed or when the specified object in the scope is destroyed. Refer to the javadocs
+or a Spring scope implementation for more information on destruction callbacks.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ void registerDestructionCallback(String name, Runnable destructionCallback)
+----
+
+The following method obtains the conversation identifier for the underlying scope. This
+identifier is different for each scope. For a session scoped implementation, this
+identifier can be the session identifier.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ String getConversationId()
+----
+
+
+[[beans-factory-scopes-custom-using]]
+===== Using a custom scope
+After you write and test one or more custom `Scope` implementations, you need to make
+the Spring container aware of your new scope(s). The following method is the central
+method to register a new `Scope` with the Spring container:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ void registerScope(String scopeName, Scope scope);
+----
+
+This method is declared on the `ConfigurableBeanFactory` interface, which is available
+on most of the concrete `ApplicationContext` implementations that ship with Spring via
+the BeanFactory property.
+
+The first argument to the `registerScope(..)` method is the unique name associated with
+a scope; examples of such names in the Spring container itself are `singleton` and
+`prototype`. The second argument to the `registerScope(..)` method is an actual instance
+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"]
+----
+ Scope threadScope = new SimpleThreadScope();
+ beanFactory.registerScope("thread", threadScope);
+----
+
+You then create bean definitions that adhere to the scoping rules of your custom `Scope`:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+----
+
+With a custom `Scope` implementation, you are not limited to programmatic registration
+of the scope. You can also do the `Scope` registration declaratively, using the
+`CustomScopeConfigurer` class:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+----
+
+[NOTE]
+====
+When you place `` in a `FactoryBean` implementation, it is the factory
+bean itself that is scoped, not the object returned from `getObject()`.
+====
+
+
+
+
+[[beans-factory-nature]]
+=== Customizing the nature of a bean
+
+
+
+[[beans-factory-lifecycle]]
+==== Lifecycle callbacks
+To interact with the container's management of the bean lifecycle, you can implement the
+Spring `InitializingBean` and `DisposableBean` interfaces. The container calls
+`afterPropertiesSet()` for the former and `destroy()` for the latter to allow the bean
+to perform certain actions upon initialization and destruction of your beans.
+
+[TIP]
+====
+
+The JSR-250 `@PostConstruct` and `@PreDestroy` annotations are generally considered best
+practice for receiving lifecycle callbacks in a modern Spring application. Using these
+annotations means that your beans are not coupled to Spring specific interfaces. For
+details see <>.
+
+If you don't want to use the JSR-250 annotations but you are still looking to remove
+coupling consider the use of init-method and destroy-method object definition metadata.
+====
+
+Internally, the Spring Framework uses `BeanPostProcessor` implementations to process any
+callback interfaces it can find and call the appropriate methods. If you need custom
+features or other lifecycle behavior Spring does not offer out-of-the-box, you can
+implement a `BeanPostProcessor` yourself. For more information, see
+<>.
+
+In addition to the initialization and destruction callbacks, Spring-managed objects may
+also implement the `Lifecycle` interface so that those objects can participate in the
+startup and shutdown process as driven by the container's own lifecycle.
+
+The lifecycle callback interfaces are described in this section.
+
+
+[[beans-factory-lifecycle-initializingbean]]
+===== Initialization callbacks
+The `org.springframework.beans.factory.InitializingBean` interface allows a bean to
+perform initialization work after all necessary properties on the bean have been set by
+the container. The `InitializingBean` interface specifies a single method:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ void afterPropertiesSet() throws Exception;
+----
+
+It is recommended that you do not use the `InitializingBean` interface because it
+unnecessarily couples the code to Spring. Alternatively, use
+the <> annotation or
+specify a POJO initialization method. In the case of XML-based configuration metadata,
+you use the `init-method` attribute to specify the name of the method that has a void
+no-argument signature. For example, the following definition:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+----
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class ExampleBean {
+
+ public void init() {
+ // do some initialization work
+ }
+
+ }
+----
+
+...is exactly the same as...
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+----
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class AnotherExampleBean implements InitializingBean {
+
+ public void afterPropertiesSet() {
+ // do some initialization work
+ }
+
+ }
+----
+
+but does not couple the code to Spring.
+
+
+[[beans-factory-lifecycle-disposablebean]]
+===== Destruction callbacks
+Implementing the `org.springframework.beans.factory.DisposableBean` interface allows a
+bean to get a callback when the container containing it is destroyed. The
+`DisposableBean` interface specifies a single method:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ void destroy() throws Exception;
+----
+
+It is recommended that you do not use the `DisposableBean` callback interface because it
+unnecessarily couples the code to Spring. Alternatively, use
+the <> annotation or
+specify a generic method that is supported by bean definitions. With XML-based
+configuration metadata, you use the `destroy-method` attribute on the ``. For
+example, the following definition:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+----
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class ExampleBean {
+
+ public void cleanup() {
+ // do some destruction work (like releasing pooled connections)
+ }
+
+ }
+----
+
+is exactly the same as:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+----
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class AnotherExampleBean implements DisposableBean {
+
+ public void destroy() {
+ // do some destruction work (like releasing pooled connections)
+ }
+
+ }
+----
+
+but does not couple the code to Spring.
+
+
+[[beans-factory-lifecycle-default-init-destroy-methods]]
+===== Default initialization and destroy methods
+When you write initialization and destroy method callbacks that do not use the
+Spring-specific `InitializingBean` and `DisposableBean` callback interfaces, you
+typically write methods with names such as `init()`, `initialize()`, `dispose()`, and so
+on. Ideally, the names of such lifecycle callback methods are standardized across a
+project so that all developers use the same method names and ensure consistency.
+
+You can configure the Spring container to `look` for named initialization and destroy
+callback method names on __every__ bean. This means that you, as an application
+developer, can write your application classes and use an initialization callback called
+`init()`, without having to configure an `init-method="init"` attribute with each bean
+definition. The Spring IoC container calls that method when the bean is created (and in
+accordance with the standard lifecycle callback contract described previously). This
+feature also enforces a consistent naming convention for initialization and destroy
+method callbacks.
+
+Suppose that your initialization callback methods are named `init()` and destroy
+callback methods are named `destroy()`. Your class will resemble the class in the
+following example.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public class DefaultBlogService implements BlogService {
+
+ private BlogDao blogDao;
+
+ public void setBlogDao(BlogDao blogDao) {
+ this.blogDao = blogDao;
+ }
+
+ // this is (unsurprisingly) the initialization callback method
+ public void init() {
+ if (this.blogDao == null) {
+ throw new IllegalStateException("The [blogDao] property must be set.");
+ }
+ }
+
+ }
+----
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+
+
+
+----
+
+The presence of the `default-init-method` attribute on the top-level `` element
+attribute causes the Spring IoC container to recognize a method called `init` on beans
+as the initialization method callback. When a bean is created and assembled, if the bean
+class has such a method, it is invoked at the appropriate time.
+
+You configure destroy method callbacks similarly (in XML, that is) by using the
+`default-destroy-method` attribute on the top-level `` element.
+
+Where existing bean classes already have callback methods that are named at variance
+with the convention, you can override the default by specifying (in XML, that is) the
+method name using the `init-method` and `destroy-method` attributes of the
+itself.
+
+The Spring container guarantees that a configured initialization callback is called
+immediately after a bean is supplied with all dependencies. Thus the initialization
+callback is called on the raw bean reference, which means that AOP interceptors and so
+forth are not yet applied to the bean. A target bean is fully created __first__,
+__then__ an AOP proxy (for example) with its interceptor chain is applied. If the target
+bean and the proxy are defined separately, your code can even interact with the raw
+target bean, bypassing the proxy. Hence, it would be inconsistent to apply the
+interceptors to the init method, because doing so would couple the lifecycle of the
+target bean with its proxy/interceptors and leave strange semantics when your code
+interacts directly to the raw target bean.
+
+
+[[beans-factory-lifecycle-combined-effects]]
+===== Combining lifecycle mechanisms
+As of Spring 2.5, you have three options for controlling bean lifecycle behavior: the
+<> and
+<> callback interfaces; custom
+`init()` and `destroy()` methods; and the
+<>. 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:
+
+* Methods annotated with `@PostConstruct`
+* `afterPropertiesSet()` as defined by the `InitializingBean` callback interface
+* A custom configured `init()` method
+
+Destroy methods are called in the same order:
+
+* Methods annotated with `@PreDestroy`
+* `destroy()` as defined by the `DisposableBean` callback interface
+* A custom configured `destroy()` method
+
+
+[[beans-factory-lifecycle-processor]]
+===== Startup and shutdown callbacks
+The `Lifecycle` interface defines the essential methods for any object that has its own
+lifecycle requirements (e.g. starts and stops some background process):
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public interface Lifecycle {
+
+ void start();
+
+ void stop();
+
+ boolean isRunning();
+
+ }
+----
+
+Any Spring-managed object may implement that interface. Then, when the
+`ApplicationContext` itself starts and stops, it will cascade those calls to all `Lifecycle`
+implementations defined within that context. It does this by delegating to a
+`LifecycleProcessor`:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public interface LifecycleProcessor extends Lifecycle {
+
+ void onRefresh();
+
+ void onClose();
+
+ }
+----
+
+Notice that the `LifecycleProcessor` is itself an extension of the `Lifecycle`
+interface. It also adds two other methods for reacting to the context being refreshed
+and closed.
+
+The order of startup and shutdown invocations can be important. If a "depends-on"
+relationship exists between any two objects, the dependent side will start __after__ its
+dependency, and it will stop __before__ its dependency. However, at times the direct
+dependencies are unknown. You may only know that objects of a certain type should start
+prior to objects of another type. In those cases, the `SmartLifecycle` interface defines
+another option, namely the `getPhase()` method as defined on its super-interface,
+`Phased`.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public interface Phased {
+
+ int getPhase();
+
+ }
+----
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public interface SmartLifecycle extends Lifecycle, Phased {
+
+ boolean isAutoStartup();
+
+ void stop(Runnable callback);
+
+ }
+----
+
+When starting, the objects with the lowest phase start first, and when stopping, the
+reverse order is followed. Therefore, an object that implements `SmartLifecycle` and
+whose `getPhase()` method returns `Integer.MIN_VALUE` would be among the first to start
+and the last to stop. At the other end of the spectrum, a phase value of
+`Integer.MAX_VALUE` would indicate that the object should be started last and stopped
+first (likely because it depends on other processes to be running). When considering the
+phase value, it's also important to know that the default phase for any "normal"
+`Lifecycle` object that does not implement `SmartLifecycle` would be 0. Therefore, any
+negative phase value would indicate that an object should start before those standard
+components (and stop after them), and vice versa for any positive phase value.
+
+As you can see the stop method defined by `SmartLifecycle` accepts a callback. Any
+implementation __must__ invoke that callback's `run()` method after that implementation's
+shutdown process is complete. That enables asynchronous shutdown where necessary since
+the default implementation of the `LifecycleProcessor` interface,
+`DefaultLifecycleProcessor`, will wait up to its timeout value for the group of objects
+within each phase to invoke that callback. The default per-phase timeout is 30 seconds.
+You can override the default lifecycle processor instance by defining a bean named
+"lifecycleProcessor" within the context. If you only want to modify the timeout, then
+defining the following would be sufficient:
+
+[source,xml,indent=0]
+[subs="verbatim,quotes"]
+----
+
+
+
+
+----
+
+As mentioned, the `LifecycleProcessor` interface defines callback methods for the
+refreshing and closing of the context as well. The latter will simply drive the shutdown
+process as if `stop()` had been called explicitly, but it will happen when the context is
+closing. The 'refresh' callback on the other hand enables another feature of
+`SmartLifecycle` beans. When the context is refreshed (after all objects have been
+instantiated and initialized), that callback will be invoked, and at that point the
+default lifecycle processor will check the boolean value returned by each
+`SmartLifecycle` object's `isAutoStartup()` method. If "true", then that object will be
+started at that point rather than waiting for an explicit invocation of the context's or
+its own `start()` method (unlike the context refresh, the context start does not happen
+automatically for a standard context implementation). The "phase" value as well as any
+"depends-on" relationships will determine the startup order in the same way as described
+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
+JVM. Doing so ensures a graceful shutdown and calls the relevant destroy methods on your
+singleton beans so that all resources are released. Of course, you must still configure
+and implement these destroy callbacks correctly.
+
+To register a shutdown hook, you call the `registerShutdownHook()` method that is
+declared on the `AbstractApplicationContext` class:
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ import org.springframework.context.support.AbstractApplicationContext;
+ import org.springframework.context.support.ClassPathXmlApplicationContext;
+
+ public final class Boot {
+
+ public static void main(final String[] args) throws Exception {
+
+ AbstractApplicationContext ctx = new ClassPathXmlApplicationContext(
+ new String []{"beans.xml"});
+
+ // add a shutdown hook for the above context...
+ ctx.registerShutdownHook();
+
+ // app runs here...
+
+ // main method exits, hook is called prior to the app shutting down...
+
+ }
+ }
+----
+
+
+
+[[beans-factory-aware]]
+==== ApplicationContextAware and BeanNameAware
+
+When an `ApplicationContext` creates an object instance that implements the
+`org.springframework.context.ApplicationContextAware` interface, the instance is provided
+with a reference to that `ApplicationContext`.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public interface ApplicationContextAware {
+
+ void setApplicationContext(ApplicationContext applicationContext) throws BeansException;
+
+ }
+----
+
+Thus beans can manipulate programmatically the `ApplicationContext` that created them,
+through the `ApplicationContext` interface, or by casting the reference to a known
+subclass of this interface, such as `ConfigurableApplicationContext`, which exposes
+additional functionality. One use would be the programmatic retrieval of other beans.
+Sometimes this capability is useful; however, in general you should avoid it, because it
+couples the code to Spring and does not follow the Inversion of Control style, where
+collaborators are provided to beans as properties. Other methods of the
+`ApplicationContext` provide access to file resources, publishing application events, and
+accessing a `MessageSource`. These additional features are described in
+<>
+
+As of Spring 2.5, autowiring is another alternative to obtain reference to the
+`ApplicationContext`. The "traditional" `constructor` and `byType` autowiring modes (as
+described in <>) can provide a dependency of type
+`ApplicationContext` for a constructor argument or setter method parameter,
+respectively. For more flexibility, including the ability to autowire fields and
+multiple parameter methods, use the new annotation-based autowiring features. If you do,
+the `ApplicationContext` is autowired into a field, constructor argument, or method
+parameter that is expecting the `ApplicationContext` type if the field, constructor, or
+method in question carries the `@Autowired` annotation. For more information, see
+<>.
+
+When an `ApplicationContext` creates a class that implements the
+`org.springframework.beans.factory.BeanNameAware` interface, the class is provided with
+a reference to the name defined in its associated object definition.
+
+[source,java,indent=0]
+[subs="verbatim,quotes"]
+----
+ public interface BeanNameAware {
+
+ void setBeanName(string name) throws BeansException;
+
+ }
+----
+
+The callback is invoked after population of normal bean properties but before an
+initialization callback such as `InitializingBean` __afterPropertiesSet__ or a custom
+init-method.
+
+
+
+[[aware-list]]
+==== Other Aware interfaces
+
+Besides `ApplicationContextAware` and `BeanNameAware` discussed above, Spring offers a
+range of `Aware` interfaces that allow beans to indicate to the container that they
+require a certain __infrastructure__ dependency. The most important `Aware` interfaces
+are summarized below - as a general rule, the name is a good indication of the
+dependency type:
+
+[[beans-factory-nature-aware-list]]
+.Aware interfaces
+|===
+| Name| Injected Dependency| Explained in...
+
+| `ApplicationContextAware`
+| Declaring `ApplicationContext`
+| <>
+
+| `ApplicationEventPublisherAware`
+| Event publisher of the enclosing `ApplicationContext`
+| <>
+
+| `BeanClassLoaderAware`
+| Class loader used to load the bean classes.
+| <>
+
+| `BeanFactoryAware`
+| Declaring `BeanFactory`
+| <>
+
+| `BeanNameAware`
+| Name of the declaring bean
+| <>
+
+| `BootstrapContextAware`
+| Resource adapter `BootstrapContext` the container runs in. Typically available only in
+ JCA aware ++ApplicationContext++s
+| <>
+
+| `LoadTimeWeaverAware`
+| Defined __weaver__ for processing class definition at load time
+| <>
+
+| `MessageSourceAware`
+| Configured strategy for resolving messages (with support for parametrization and
+ internationalization)
+| <>
+
+| `NotificationPublisherAware`
+| Spring JMX notification publisher
+| <