diff --git a/spring-framework-reference/src/aop-api.xml b/spring-framework-reference/src/aop-api.xml
index 1225181c839..eeed54240fe 100644
--- a/spring-framework-reference/src/aop-api.xml
+++ b/spring-framework-reference/src/aop-api.xml
@@ -33,7 +33,7 @@
is the central interface, used to target advices to particular classes
and methods. The complete interface is shown below:
- matches() method always returns true, all target
classes will be matched:
-
@@ -59,7 +59,7 @@
The MethodMatcher interface is normally more
important. The complete interface is shown below:
- The usage is shown below:
- <bean id="settersAndAbsquatulatePointcut"
+ <bean id="settersAndAbsquatulatePointcut"
class="org.springframework.aop.support.Perl5RegexpMethodPointcut">
<property name="patterns">
<list>
@@ -189,7 +189,7 @@
as the one bean encapsulates both pointcut and advice, as shown
below:
- <bean id="settersAndAbsquatulateAdvisor"
+ <bean id="settersAndAbsquatulateAdvisor"
class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<ref local="beanNameOfAopAllianceInterceptor"/>
@@ -260,7 +260,7 @@
just one abstract method (although it's possible to override other
methods to customize behavior):
- class TestStaticPointcut extends StaticMethodMatcherPointcut {
+ class TestStaticPointcut extends StaticMethodMatcherPointcut {
public boolean matches(Method m, Class targetClass) {
// return true if custom criteria match
@@ -332,7 +332,7 @@
advice using method interception. MethodInterceptors implementing
around advice should implement the following interface:
- public interface MethodInterceptor extends Interceptor {
+ public interface MethodInterceptor extends Interceptor {
Object invoke(MethodInvocation invocation) throws Throwable;
}
@@ -346,7 +346,7 @@
A simple MethodInterceptor implementation
looks as follows:
- public class DebugInterceptor implements MethodInterceptor {
+ public class DebugInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("Before: invocation=[" + invocation + "]");
@@ -393,7 +393,7 @@
although the usual objects apply to field interception and it's
unlikely that Spring will ever implement it).
- public interface MethodBeforeAdvice extends BeforeAdvice {
+ public interface MethodBeforeAdvice extends BeforeAdvice {
void before(Method m, Object[] args, Object target) throws Throwable;
}
@@ -410,7 +410,7 @@
An example of a before advice in Spring, which counts all method
invocations:
- public class CountingBeforeAdvice implements MethodBeforeAdvice {
+ public class CountingBeforeAdvice implements MethodBeforeAdvice {
private int count;
@@ -437,7 +437,7 @@
given object implements one or more typed throws advice methods. These
should be in the form of:
- afterThrowing([Method, args, target], subclassOfThrowable)
+ 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
@@ -447,7 +447,7 @@
The advice below is invoked if a RemoteException
is thrown (including subclasses):
- // Do something with remote exception
- // Do something with all argumentsServletException. Any number of throws advice
methods can be combined in a single class.
- public static class CombinedThrowsAdvice implements ThrowsAdvice {
+ public static class CombinedThrowsAdvice implements ThrowsAdvice {
public void afterThrowing(RemoteException ex) throws Throwable {
// Do something with remote exception
@@ -501,7 +501,7 @@
org.springframework.aop.AfterReturningAdvice
interface, shown below:
- public interface AfterReturningAdvice extends Advice {
+ public interface AfterReturningAdvice extends Advice {
void afterReturning(Object returnValue, Method m, Object[] args, Object target)
throws Throwable;
@@ -514,7 +514,7 @@
The following after returning advice counts all successful
method invocations that have not thrown exceptions:
- public class CountingAfterReturningAdvice implements AfterReturningAdvice {
+ public class CountingAfterReturningAdvice implements AfterReturningAdvice {
private int count;
@@ -543,7 +543,7 @@
and an IntroductionInterceptor, implementing the
following interface:
- public interface IntroductionInterceptor extends MethodInterceptor {
+ public interface IntroductionInterceptor extends MethodInterceptor {
boolean implementsInterface(Class intf);
}
@@ -563,7 +563,7 @@
- public interface IntroductionAdvisor extends Advisor, IntroductionInfo {
+ public interface IntroductionAdvisor extends Advisor, IntroductionInfo {
ClassFilter getClassFilter();
@@ -603,7 +603,7 @@ public interface IntroductionInfo {
- public interface Lockable {
+ public interface Lockable {
void lock();
void unlock();
boolean locked();
@@ -672,7 +672,7 @@ public interface IntroductionInfo {
- public class LockMixin extends DelegatingIntroductionInterceptor
+ public class LockMixin extends DelegatingIntroductionInterceptor
implements Lockable {
private boolean locked;
@@ -722,7 +722,7 @@ public interface IntroductionInfo {
- public class LockMixinAdvisor extends DefaultIntroductionAdvisor {
+ public class LockMixinAdvisor extends DefaultIntroductionAdvisor {
public LockMixinAdvisor() {
super(new LockMixin(), Lockable.class);
@@ -1032,7 +1032,7 @@ public interface IntroductionInfo {
- <bean id="personTarget" class="com.mycompany.PersonImpl">
+ <bean id="personTarget" class="com.mycompany.PersonImpl">
<property name="name"><value>Tony</value></property>
<property name="age"><value>51</value></property>
</bean>
@@ -1076,12 +1076,12 @@ public interface IntroductionInfo {
The "person" bean definition above can be used in place of a
Person implementation, as follows:
- Person person = (Person) factory.getBean("person");
+ 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:
- <bean id="personUser" class="com.mycompany.PersonUser">
+ <bean id="personUser" class="com.mycompany.PersonUser">
<property name="person"><ref local="person" /></property>
</bean>
@@ -1097,7 +1097,7 @@ public interface IntroductionInfo {
ProxyFactoryBean definition is different; the advice
is included only for completeness:
- <bean id="myAdvisor" class="com.mycompany.MyAdvisor">
+ <bean id="myAdvisor" class="com.mycompany.MyAdvisor">
<property name="someProperty"><value>Custom string property value</value></property>
</bean>
@@ -1184,7 +1184,7 @@ public interface IntroductionInfo {
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:
+ of 'global' advisors:
<bean id="proxy" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="service"/>
<property name="interceptorNames">
@@ -1211,7 +1211,7 @@ public interface IntroductionInfo {
First a parent, template, bean definition is
created for the proxy:
- <bean id="txProxyTemplate" abstract="true"
+ <bean id="txProxyTemplate" abstract="true"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager" ref="transactionManager"/>
<property name="transactionAttributes">
@@ -1225,7 +1225,7 @@ public interface IntroductionInfo {
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.<bean id="myService" parent="txProxyTemplate">
+ anyway.<bean id="myService" parent="txProxyTemplate">
<property name="target">
<bean class="org.springframework.samples.MyServiceImpl">
</bean>
@@ -1234,7 +1234,7 @@ public interface IntroductionInfo {
It is of course possible to override properties from the parent
template, such as in this case, the transaction propagation
- settings:<bean id="mySpecialService" parent="txProxyTemplate">
+ settings:<bean id="mySpecialService" parent="txProxyTemplate">
<property name="target">
<bean class="org.springframework.samples.MySpecialServiceImpl">
</bean>
@@ -1273,7 +1273,7 @@ public interface IntroductionInfo {
with one interceptor and one advisor. The interfaces implemented by the
target object will automatically be proxied:
- ProxyFactory factory = new ProxyFactory(myBusinessInterfaceImpl);
+ ProxyFactory factory = new ProxyFactory(myBusinessInterfaceImpl);
factory.addInterceptor(myMethodInterceptor);
factory.addAdvisor(myAdvisor);
MyBusinessInterface tb = (MyBusinessInterface) factory.getProxy();
@@ -1308,7 +1308,7 @@ MyBusinessInterface tb = (MyBusinessInterface) factory.getProxy();
- Advisor[] getAdvisors();
+ Advisor[] getAdvisors();
void addAdvice(Advice advice) throws AopConfigException;
@@ -1355,7 +1355,7 @@ boolean isFrozen();Advised interface and examining and manipulating its
advice:
- Advised advised = (Advised) myObject;
+ Advised advised = (Advised) myObject;
Advisor[] advisors = advised.getAdvisors();
int oldAdvisorCount = advisors.length;
System.out.println(oldAdvisorCount + " advisors");
@@ -1438,7 +1438,7 @@ assertEquals("Added two advisors",
BeanPostProcessor that automatically creates AOP proxies
for beans with names matching literal values or wildcards.
- <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
+ <bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames"><value>jdk*,onlyJdk</value></property>
<property name="interceptorNames">
<list>
@@ -1513,7 +1513,7 @@ assertEquals("Added two advisors",
return an AOP proxy, not the target business object. (The "inner bean"
idiom shown earlier also offers this benefit.)
- <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>
+ <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>
<bean class="org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor">
<property name="transactionInterceptor" ref="transactionInterceptor"/>
@@ -1586,7 +1586,7 @@ assertEquals("Added two advisors",
following code, in /WEB-INF/declarativeServices.xml.
Note that this is generic, and can be used outside the JPetStore:
- <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>
+ <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>
<bean class="org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor">
<property name="transactionInterceptor" ref="transactionInterceptor"/>
@@ -1627,7 +1627,7 @@ assertEquals("Added two advisors",
annotation, leading to implicit proxies for beans containing that
annotation:
- <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>
+ <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"/>
<bean class="org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor">
<property name="transactionInterceptor" ref="transactionInterceptor"/>
@@ -1647,7 +1647,7 @@ assertEquals("Added two advisors",
be specific to the application's transaction requirements (typically
JTA, as in this example, or Hibernate, JDO or JDBC):
- <bean id="transactionManager"
+ <bean id="transactionManager"
class="org.springframework.transaction.jta.JtaTransactionManager"/>
@@ -1684,7 +1684,7 @@ assertEquals("Added two advisors",
generic DefaultPointcutAdvisor, configured using
JavaBean properties:
- <bean id="lockMixin" class="org.springframework.aop.LockMixin"
+ <bean id="lockMixin" class="org.springframework.aop.LockMixin"
scope="prototype"/>
<bean id="lockableAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor"
@@ -1748,13 +1748,13 @@ assertEquals("Added two advisors",
You can change the target via the swap() method
on HotSwappableTargetSource as follows:
- HotSwappableTargetSource swapper =
+ HotSwappableTargetSource swapper =
(HotSwappableTargetSource) beanFactory.getBean("swapper");
Object oldTarget = swapper.swap(newTarget);The XML definitions required look as follows:
- <bean id="initialTarget" class="mycompany.OldTarget"/>
+ <bean id="initialTarget" class="mycompany.OldTarget"/>
<bean id="swapper" class="org.springframework.aop.target.HotSwappableTargetSource">
<constructor-arg ref="initialTarget"/>
@@ -1796,7 +1796,7 @@ Object oldTarget = swapper.swap(newTarget);Sample configuration is shown below:
- <bean id="businessObjectTarget" class="com.mycompany.MyBusinessObject"
+ <bean id="businessObjectTarget" class="com.mycompany.MyBusinessObject"
scope="prototype">
... properties omitted
</bean>
@@ -1832,7 +1832,7 @@ Object oldTarget = swapper.swap(newTarget);
size of the pool through an introduction. You'll need to define an
advisor like this:
- <bean id="poolConfigAdvisor" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
+ <bean id="poolConfigAdvisor" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="poolTargetSource"/>
<property name="targetMethod" value="getPoolingConfigMixin"/>
</bean>
@@ -1845,7 +1845,7 @@ Object oldTarget = swapper.swap(newTarget);The cast will look as follows:
-
@@ -1873,7 +1873,7 @@ System.out.println("Max pool size is " + conf.getMaxSize());]]>poolTargetSource definition shown above as follows.
(I've also changed the name, for clarity.)
-
+
]]>
@@ -1893,7 +1893,7 @@ System.out.println("Max pool size is " + conf.getMaxSize());]]>ThreadLocalTargetSource is pretty much the same as was explained for the
other types of target source:
-
+
]]>
diff --git a/spring-framework-reference/src/aop.xml b/spring-framework-reference/src/aop.xml
index 1fd774a74ca..6fb7a9d797e 100644
--- a/spring-framework-reference/src/aop.xml
+++ b/spring-framework-reference/src/aop.xml
@@ -327,7 +327,7 @@
The @AspectJ support is enabled by including the following element
inside your spring configuration:
- <aop:aspectj-autoproxy/>
+ <aop:aspectj-autoproxy/>This assumes that you are using schema support as described in
. See
- <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />
+ <bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />You will also need two AspectJ libraries on the classpath of your
application: aspectjweaver.jar
@@ -364,7 +364,7 @@
a bean class that has the @Aspect
annotation:
- <bean id="myAspect" class="org.xyz.NotVeryUsefulAspect">
+ <bean id="myAspect" class="org.xyz.NotVeryUsefulAspect">
<!-- configure properties of aspect here as normal -->
</bean>
@@ -374,7 +374,7 @@
org.aspectj.lang.annotation.Aspect
annotation;
- package org.xyz;
+ package org.xyz;
import org.aspectj.lang.annotation.Aspect;
@Aspect
@@ -419,7 +419,7 @@ public class NotVeryUsefulAspect {
a pointcut named 'anyOldTransfer' that will match the
execution of any method named 'transfer':
- @Pointcut("execution(* transfer(..))")// the pointcut expression
+ @Pointcut("execution(* transfer(..))")// the pointcut expression
private void anyOldTransfer() {}// the pointcut signatureThe pointcut expression that forms the value of the
@@ -550,7 +550,7 @@ private void anyOldTransfer() {}// the pointcut signaturebean' PCD
has the following form:
- bean(idOrNameOfBean)
+ bean(idOrNameOfBean)The 'idOrNameOfBean' token can be the name of
any Spring bean: limited wildcard support using the
@@ -592,7 +592,7 @@ private void anyOldTransfer() {}// the pointcut signature
- @Pointcut("execution(public * *(..))")
+ @Pointcut("execution(public * *(..))")
private void anyPublicOperation() {}
@Pointcut("within(com.xyz.someapp.trading..*)")
@@ -618,7 +618,7 @@ private void anyOldTransfer() {}// the pointcut signature
- package com.xyz.someapp;
+ package com.xyz.someapp;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
@@ -681,7 +681,7 @@ public class SystemArchitecture {
anywhere that you need a pointcut expression. For example, to make the
service layer transactional, you could write:
- <aop:config>
+ <aop:config>
<aop:advisor
pointcut="com.xyz.someapp.SystemArchitecture.businessService()"
advice-ref="tx-advice"/>
@@ -706,7 +706,7 @@ public class SystemArchitecture {
execution pointcut designator the most often. The
format of an execution expression is:
- execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern)
+ 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
@@ -736,49 +736,49 @@ public class SystemArchitecture {
the execution of any public method:
- execution(public * *(..))
+ execution(public * *(..))the execution of any method with a name beginning with
"set":
- execution(* set*(..))
+ execution(* set*(..))the execution of any method defined by the
AccountService interface:
- execution(* com.xyz.service.AccountService.*(..))
+ execution(* com.xyz.service.AccountService.*(..))the execution of any method defined in the service
package:
- execution(* com.xyz.service.*.*(..))
+ execution(* com.xyz.service.*.*(..))the execution of any method defined in the service package
or a sub-package:
- execution(* com.xyz.service..*.*(..))
+ execution(* com.xyz.service..*.*(..))any join point (method execution only in Spring AOP) within
the service package:
- within(com.xyz.service.*)
+ within(com.xyz.service.*)any join point (method execution only in Spring AOP) within
the service package or a sub-package:
- within(com.xyz.service..*)
+ within(com.xyz.service..*)
@@ -786,7 +786,7 @@ public class SystemArchitecture {
the proxy implements the
AccountService interface:
- this(com.xyz.service.AccountService)
+ this(com.xyz.service.AccountService)'this' is more commonly used in a binding form :-
see the following section on advice for how to make the proxy
@@ -798,7 +798,7 @@ public class SystemArchitecture {
the target object implements the
AccountService interface:
- target(com.xyz.service.AccountService)
+ target(com.xyz.service.AccountService)'target' is more commonly used in a binding form :-
see the following section on advice for how to make the target
@@ -810,7 +810,7 @@ public class SystemArchitecture {
takes a single parameter, and where the argument passed at runtime
is Serializable:
- args(java.io.Serializable)
+ args(java.io.Serializable)'args' is more commonly used in a binding form :- see the
following section on advice for how to make the method arguments
@@ -829,7 +829,7 @@ public class SystemArchitecture {
the target object has an
@Transactional annotation:
- @target(org.springframework.transaction.annotation.Transactional)
+ @target(org.springframework.transaction.annotation.Transactional)'@target' can also be used in a binding form :- see
the following section on advice for how to make the annotation
@@ -841,7 +841,7 @@ public class SystemArchitecture {
the declared type of the target object has an
@Transactional annotation:
- @within(org.springframework.transaction.annotation.Transactional)
+ @within(org.springframework.transaction.annotation.Transactional)'@within' can also be used in a binding form :- see
the following section on advice for how to make the annotation
@@ -853,7 +853,7 @@ public class SystemArchitecture {
the executing method has an
@Transactional annotation:
- @annotation(org.springframework.transaction.annotation.Transactional)
+ @annotation(org.springframework.transaction.annotation.Transactional)'@annotation' can also be used in a binding form :-
see the following section on advice for how to make the annotation
@@ -866,7 +866,7 @@ public class SystemArchitecture {
argument passed has the @Classified
annotation:
- @args(com.xyz.security.Classified)
+ @args(com.xyz.security.Classified)'@args' can also be used in a binding form :- see
the following section on advice for how to make the annotation
@@ -877,7 +877,7 @@ public class SystemArchitecture {
any join point (method execution only in Spring AOP) on a
Spring bean named 'tradeService':
- bean(tradeService)
+ bean(tradeService)
@@ -885,7 +885,7 @@ public class SystemArchitecture {
Spring beans having names that match the wildcard expression
'*Service':
- bean(*Service)
+ bean(*Service)
@@ -905,7 +905,7 @@ public class SystemArchitecture {
Before advice is declared in an aspect using the
@Before annotation:
- import org.aspectj.lang.annotation.Aspect;
+ import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
@@ -921,7 +921,7 @@ public class BeforeExample {
If using an in-place pointcut expression we could rewrite the
above example as:
- import org.aspectj.lang.annotation.Aspect;
+ import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
@@ -942,7 +942,7 @@ public class BeforeExample {
returns normally. It is declared using the
@AfterReturning annotation:
- import org.aspectj.lang.annotation.Aspect;
+ import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterReturning;
@Aspect
@@ -965,7 +965,7 @@ public class AfterReturningExample {
@AfterReturning that binds the return
value for this:
- import org.aspectj.lang.annotation.Aspect;
+ import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterReturning;
@Aspect
@@ -1001,7 +1001,7 @@ public class AfterReturningExample {
by throwing an exception. It is declared using the
@AfterThrowing annotation:
- import org.aspectj.lang.annotation.Aspect;
+ import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterThrowing;
@Aspect
@@ -1022,7 +1022,7 @@ public class AfterThrowingExample {
otherwise) and bind the thrown exception to an advice
parameter.
- import org.aspectj.lang.annotation.Aspect;
+ import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.AfterThrowing;
@Aspect
@@ -1055,7 +1055,7 @@ public class AfterThrowingExample {
exception return conditions. It is typically used for releasing
resources, etc.
- import org.aspectj.lang.annotation.Aspect;
+ import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.After;
@Aspect
@@ -1111,7 +1111,7 @@ public class AfterFinallyExample {
AspectJ, and this is discussed in the following section on advice
parameters.
- import org.aspectj.lang.annotation.Aspect;
+ import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.ProceedingJoinPoint;
@@ -1184,7 +1184,7 @@ public class AroundExample {
Account object as the first parameter, and you need access to the
account in the advice body. You could write the following:
- @Before("com.xyz.myapp.SystemArchitecture.dataAccessOperation() &&" +
+ @Before("com.xyz.myapp.SystemArchitecture.dataAccessOperation() &&" +
"args(account,..)")
public void validateAccount(Account account) {
// ...
@@ -1203,7 +1203,7 @@ public void validateAccount(Account account) {
matches a join point, and then just refer to the named pointcut from
the advice. This would look as follows:
- @Pointcut("com.xyz.myapp.SystemArchitecture.dataAccessOperation() &&" +
+ @Pointcut("com.xyz.myapp.SystemArchitecture.dataAccessOperation() &&" +
"args(account,..)")
private void accountDataAccessOperation(Account account) {}
@@ -1226,7 +1226,7 @@ public void validateAccount(Account account) {
First the definition of the
@Auditable annotation:
- @Retention(RetentionPolicy.RUNTIME)
+ @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Auditable {
AuditCode value();
@@ -1235,7 +1235,7 @@ public @interface Auditable {
And then the advice that matches the execution of
@Auditable methods:
- @Before("com.xyz.lib.Pointcuts.anyPublicMethod() && " +
+ @Before("com.xyz.lib.Pointcuts.anyPublicMethod() && " +
"@annotation(auditable)")
public void audit(Auditable auditable) {
AuditCode code = auditable.value();
@@ -1263,7 +1263,7 @@ public void audit(Auditable auditable) {
are available at runtime. For
example:
- @Before(
+ @Before(
value="com.xyz.lib.Pointcuts.anyPublicMethod() && target(bean) && @annotation(auditable)",
argNames="bean,auditable")
public void audit(Object bean, Auditable auditable) {
@@ -1280,7 +1280,7 @@ public void audit(Object bean, Auditable auditable) {
advice to receive the join point object, the "argNames"
attribute need not include it:
- @Before(
+ @Before(
value="com.xyz.lib.Pointcuts.anyPublicMethod() && target(bean) && @annotation(auditable)",
argNames="bean,auditable")
public void audit(JoinPoint jp, Object bean, Auditable auditable) {
@@ -1297,7 +1297,7 @@ public void audit(JoinPoint jp, Object bean, Auditable auditable) {
"argNames" attribute. For example, the following advice need not
declare the "argNames" attribute:
- @Before(
+ @Before(
"com.xyz.lib.Pointcuts.anyPublicMethod()")
public void audit(JoinPoint jp) {
// ... use jp
@@ -1355,7 +1355,7 @@ public void audit(JoinPoint jp) {
to ensure that the advice signature binds each of the method
parameters in order. For example:
- @Around("execution(List<Account> find*(..)) &&" +
+ @Around("execution(List<Account> find*(..)) &&" +
"com.xyz.myapp.SystemArchitecture.inDataAccessLayer() && " +
"args(accountHolderNamePattern)")
public Object preProcessQueryPattern(ProceedingJoinPoint pjp, String accountHolderNamePattern)
@@ -1423,7 +1423,7 @@ throws Throwable {
implement the UsageTracked interface. (In
order to expose statistics via JMX for example.)
- @Aspect
+ @Aspect
public class UsageTracking {
@DeclareParents(value="com.xzy.myapp.service.*+",
@@ -1447,7 +1447,7 @@ public class UsageTracking {
UsageTracked interface. If accessing a
bean programmatically you would write the following:
- UsageTracked usageTracked = (UsageTracked) context.getBean("myService");
+ UsageTracked usageTracked = (UsageTracked) context.getBean("myService");
@@ -1469,7 +1469,7 @@ public class UsageTracking {
@Aspect annotation. Let's look at an
example, and then we'll explain how it works.
- @Aspect("perthis(com.xyz.myapp.SystemArchitecture.businessService())")
+ @Aspect("perthis(com.xyz.myapp.SystemArchitecture.businessService())")
public class MyAspect {
private int someState;
@@ -1519,7 +1519,7 @@ public class MyAspect {
advice so that we can call proceed multiple times. Here's how the basic
aspect implementation looks:
- @Aspect
+ @Aspect
public class ConcurrentOperationExecutor implements Ordered {
private static final int DEFAULT_MAX_RETRIES = 2;
@@ -1573,7 +1573,7 @@ public class ConcurrentOperationExecutor implements Ordered {
The corresponding Spring configuration is:
- <aop:aspectj-autoproxy/>
+ <aop:aspectj-autoproxy/>
<bean id="concurrentOperationExecutor"
class="com.xyz.myapp.service.impl.ConcurrentOperationExecutor">
@@ -1585,7 +1585,7 @@ public class ConcurrentOperationExecutor implements Ordered {
operations, we might define an Idempotent
annotation:
- @Retention(RetentionPolicy.RUNTIME)
+ @Retention(RetentionPolicy.RUNTIME)
public @interface Idempotent {
// marker annotation
}
@@ -1595,7 +1595,7 @@ public @interface Idempotent {
simply involves refining the pointcut expression so that only
@Idempotent operations match:
- @Around("com.xyz.myapp.SystemArchitecture.businessService() && " +
+ @Around("com.xyz.myapp.SystemArchitecture.businessService() && " +
"@annotation(com.xyz.myapp.service.Idempotent)")
public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
...
@@ -1653,7 +1653,7 @@ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
the backing bean is referenced using the ref
attribute:
- <aop:config>
+ <aop:config>
<aop:aspect id="myAspect" ref="aBean">
...
</aop:aspect>
@@ -1678,7 +1678,7 @@ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
A pointcut representing the execution of any business service in
the service layer could be defined as follows:
- <aop:config>
+ <aop:config>
<aop:pointcut id="businessService"
expression="execution(* com.xyz.myapp.service.*.*(..))"/>
@@ -1694,7 +1694,7 @@ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
AspectJ reflection APIs). On JDK 1.5 therefore, another way of defining
the above pointcut would be:
- <aop:config>
+ <aop:config>
<aop:pointcut id="businessService"
expression="com.xyz.myapp.SystemArchitecture.businessService()"/>
@@ -1707,7 +1707,7 @@ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
Declaring a pointcut inside an aspect is very similar to declaring
a top-level pointcut:
- <aop:config>
+ <aop:config>
<aop:aspect id="myAspect" ref="aBean">
@@ -1725,7 +1725,7 @@ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
example, the following pointcut collects the 'this' object as the join
point context and passes it to advice:
- <aop:config>
+ <aop:config>
<aop:aspect id="myAspect" ref="aBean">
@@ -1741,7 +1741,7 @@ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
The advice must be declared to receive the collected join point
context by including parameters of the matching names:
- public void monitor(Object service) {
+ public void monitor(Object service) {
...
}
@@ -1750,7 +1750,7 @@ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
used in place of '&&', '||' and '!' respectively. For example,
the previous pointcut may be better written as:
- <aop:config>
+ <aop:config>
<aop:aspect id="myAspect" ref="aBean">
@@ -1784,7 +1784,7 @@ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
declared inside an <aop:aspect> using the
<aop:before> element.
- <aop:aspect id="beforeExample" ref="aBean">
+ <aop:aspect id="beforeExample" ref="aBean">
<aop:before
pointcut-ref="dataAccessOperation"
@@ -1800,7 +1800,7 @@ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
pointcut-ref attribute with a
pointcut attribute:
- <aop:aspect id="beforeExample" ref="aBean">
+ <aop:aspect id="beforeExample" ref="aBean">
<aop:before
pointcut="execution(* com.xyz.myapp.dao.*.*(..))"
@@ -1831,7 +1831,7 @@ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
<aop:aspect> in the same way as before
advice. For example:
- <aop:aspect id="afterReturningExample" ref="aBean">
+ <aop:aspect id="afterReturningExample" ref="aBean">
<aop:after-returning
pointcut-ref="dataAccessOperation"
@@ -1846,7 +1846,7 @@ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
specify the name of the parameter to which the return value should be
passed:
- <aop:aspect id="afterReturningExample" ref="aBean">
+ <aop:aspect id="afterReturningExample" ref="aBean">
<aop:after-returning
pointcut-ref="dataAccessOperation"
@@ -1862,7 +1862,7 @@ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
matching in the same way as described for @AfterReturning. For
example, the method signature may be declared as:
- public void doAccessCheck(Object retVal) {...
+ public void doAccessCheck(Object retVal) {...
@@ -1873,7 +1873,7 @@ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
<aop:aspect> using the after-throwing
element:
- <aop:aspect id="afterThrowingExample" ref="aBean">
+ <aop:aspect id="afterThrowingExample" ref="aBean">
<aop:after-throwing
pointcut-ref="dataAccessOperation"
@@ -1888,7 +1888,7 @@ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
specify the name of the parameter to which the exception should be
passed:
- <aop:aspect id="afterThrowingExample" ref="aBean">
+ <aop:aspect id="afterThrowingExample" ref="aBean">
<aop:after-throwing
pointcut-ref="dataAccessOperation"
@@ -1904,7 +1904,7 @@ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
matching in the same way as described for @AfterThrowing. For example,
the method signature may be declared as:
- public void doRecoveryActions(DataAccessException dataAccessEx) {...
+ public void doRecoveryActions(DataAccessException dataAccessEx) {...
@@ -1914,7 +1914,7 @@ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
exits. It is declared using the after
element:
- <aop:aspect id="afterFinallyExample" ref="aBean">
+ <aop:aspect id="afterFinallyExample" ref="aBean">
<aop:after
pointcut-ref="dataAccessOperation"
@@ -1951,7 +1951,7 @@ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
linkend="aop-ataspectj-around-advice" /> for notes on calling proceed
with an Object[].
- <aop:aspect id="aroundExample" ref="aBean">
+ <aop:aspect id="aroundExample" ref="aBean">
<aop:around
pointcut-ref="businessService"
@@ -1965,7 +1965,7 @@ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
advice would be exactly the same as in the @AspectJ example (minus the
annotation of course):
- public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
+ public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
// start stopwatch
Object retVal = pjp.proceed();
// stop stopwatch
@@ -1987,7 +1987,7 @@ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
attribute in an advice annotation as described in . For example:
- <aop:before
+ <aop:before
pointcut="com.xyz.lib.Pointcuts.anyPublicMethod() and @annotation(auditable)"
method="audit"
arg-names="auditable"/>
@@ -1999,7 +1999,7 @@ public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
approach that illustrates some around advice used in conjunction with
a number of strongly typed parameters.
- package x.y.service;
+ package x.y.service;
public interface FooService {
@@ -2021,7 +2021,7 @@ public class DefaultFooService implements FooService {
profile(..) is to be used as
around advice:
- package x.y;
+ package x.y;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.util.StopWatch;
@@ -2045,7 +2045,7 @@ public class SimpleProfiler {
effect the execution of the above advice for a particular join
point:
- <beans xmlns="http://www.springframework.org/schema/beans"
+ <beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
@@ -2076,7 +2076,7 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/
If we had the following driver script, we would get output
something like this on standard output:
- import org.springframework.beans.factory.BeanFactory;
+ import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import x.y.service.FooService;
@@ -2128,7 +2128,7 @@ ms % Task name
UsageTracked interface. (In order to
expose statistics via JMX for example.)
- <aop:aspect id="usageTrackerAspect" ref="usageTracking">
+ <aop:aspect id="usageTrackerAspect" ref="usageTracking">
<aop:declare-parents
types-matching="com.xzy.myapp.service.*+"
@@ -2145,7 +2145,7 @@ ms % Task name
The class backing the usageTracking bean would
contain the method:
- public void recordUsage(UsageTracked usageTracked) {
+ public void recordUsage(UsageTracked usageTracked) {
usageTracked.incrementUseCount();
}
@@ -2159,7 +2159,7 @@ ms % Task name
interface. If accessing a bean programmatically you would write the
following:
- UsageTracked usageTracked = (UsageTracked) context.getBean("myService");
+ UsageTracked usageTracked = (UsageTracked) context.getBean("myService");
@@ -2186,7 +2186,7 @@ ms % Task name
see it used in conjunction with transactional advice, which also has its
own namespace support in Spring 2.0. Here's how it looks:
- <aop:config>
+ <aop:config>
<aop:pointcut id="businessService"
expression="execution(* com.xyz.myapp.service.*.*(..))"/>
@@ -2235,7 +2235,7 @@ ms % Task name
aspect implementation looks (it's just a regular Java class using the
schema support):
- public class ConcurrentOperationExecutor implements Ordered {
+ public class ConcurrentOperationExecutor implements Ordered {
private static final int DEFAULT_MAX_RETRIES = 2;
@@ -2288,7 +2288,7 @@ ms % Task name
The corresponding Spring configuration is:
- <aop:config>
+ <aop:config>
<aop:aspect id="concurrentOperationRetry" ref="concurrentOperationExecutor">
@@ -2315,7 +2315,7 @@ ms % Task name
introducing an Idempotent
annotation:
- @Retention(RetentionPolicy.RUNTIME)
+ @Retention(RetentionPolicy.RUNTIME)
public @interface Idempotent {
// marker annotation
}
@@ -2325,7 +2325,7 @@ public @interface Idempotent {
simply involves refining the pointcut expression so that only
@Idempotent operations match:
- <aop:pointcut id="idempotentOperation"
+ <aop:pointcut id="idempotentOperation"
expression="execution(* com.xyz.myapp.service.*.*(..)) and
@annotation(com.xyz.myapp.service.Idempotent)"/>
@@ -2401,7 +2401,7 @@ public @interface Idempotent {
in XML. For example, in the @AspectJ style you can write something
like:
- @Pointcut(execution(* get*()))
+ @Pointcut(execution(* get*()))
public void propertyAccess() {}
@Pointcut(execution(org.xyz.Account+ *(..))
@@ -2412,7 +2412,7 @@ public @interface Idempotent {
In the XML style I can declare the first two pointcuts:
- <aop:pointcut id="propertyAccess"
+ <aop:pointcut id="propertyAccess"
expression="execution(* get*())"/>
<aop:pointcut id="operationReturningAnAccount"
@@ -2492,7 +2492,7 @@ public @interface Idempotent {
the value of the proxy-target-class attribute of the
<aop:config> element to true:
- <aop:config proxy-target-class="true">
+ <aop:config proxy-target-class="true">
<!-- other beans defined here... -->
</aop:config>
@@ -2501,7 +2501,7 @@ public @interface Idempotent {
<aop:aspectj-autoproxy> element to
true:
- <aop:aspectj-autoproxy proxy-target-class="true"/>
+ <aop:aspectj-autoproxy proxy-target-class="true"/>Multiple <aop:config/> sections are
@@ -2531,7 +2531,7 @@ public @interface Idempotent {
un-proxied, nothing-special-about-it, straight object reference, as
illustrated by the following code snippet.
- public class SimplePojo implements Pojo {
+ public class SimplePojo implements Pojo {
public void foo() {
// this next method invocation is a
- public class Main {
+ public class Main {
public static void main(String[] args) {
@@ -2588,7 +2588,7 @@ public @interface Idempotent {
- public class Main {
+ public class Main {
public static void main(String[] args) {
@@ -2628,7 +2628,7 @@ public @interface Idempotent {
out precisely because it is so horrendous. You can (choke!) totally tie
the logic within your class to Spring AOP by doing this:
- public class SimplePojo implements Pojo {
+ public class SimplePojo implements Pojo {
public void foo() {
// this works, but... gah!
@@ -2646,7 +2646,7 @@ public @interface Idempotent {
It also requires some additional configuration when the proxy is being
created:
- public class Main {
+ public class Main {
public static void main(String[] args) {
@@ -2685,7 +2685,7 @@ public @interface Idempotent {
or more @AspectJ aspects. Basic usage for this class is very simple, as
illustrated below. See the Javadocs for full information.
- // create a factory that can generate a proxy for the given target object
+ // 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
@@ -2739,7 +2739,7 @@ MyInterfaceType proxy = factory.getProxy();
a class as eligible for Spring-driven configuration. In the simplest
case it can be used just as a marker annotation:
- package com.xyz.myapp.domain;
+ package com.xyz.myapp.domain;
import org.springframework.beans.factory.annotation.Configurable;
@@ -2757,14 +2757,14 @@ public class Account {
way to declare the prototype definition is simply to omit the
id attribute:
- <bean class="com.xyz.myapp.domain.Account" scope="prototype">
+ <bean class="com.xyz.myapp.domain.Account" scope="prototype">
<property name="fundsTransferService" ref="fundsTransferService"/>
</bean>If you want to explicitly specify the name of the prototype bean
definition to use, you can do so directly in the annotation:
- package com.xyz.myapp.domain;
+ package com.xyz.myapp.domain;
import org.springframework.beans.factory.annotation.Configurable;
@@ -2827,7 +2827,7 @@ public class Account {
@Configurable declaration like
so:
- @Configurable(preConstruction=true)
+ @Configurable(preConstruction=true)You can find out more information about the language semantics
of the various pointcut types in AspectJ defines a convenient tag for doing this: just include
the following in your application context configuration:
- <context:spring-configured/>
+ <context:spring-configured/>If you are using the DTD instead of schema, the equivalent
definition is:
- <bean
+ <bean
class="org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect"
factory-method="aspectOf"/>
@@ -2868,7 +2868,7 @@ public class Account {
manually specify that the bean depends on the configuration
aspect.
- <bean id="myService"
+ <bean id="myService"
class="com.xzy.myapp.service.MyService"
depends-on="org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect">
@@ -2982,7 +2982,7 @@ public class Account {
domain model using prototype bean definitions that match the
fully-qualified class names:
- public aspect DomainObjectConfiguration extends AbstractBeanConfigurerAspect {
+ public aspect DomainObjectConfiguration extends AbstractBeanConfigurerAspect {
public DomainObjectConfiguration() {
setBeanWiringInfoResolver(new ClassNameBeanWiringInfoResolver());
@@ -3014,7 +3014,7 @@ public class Account {
ensures that Spring obtains the aspect instance by asking AspectJ for it
rather than trying to create an instance itself. For example:
- <bean id="profiler" class="com.xyz.profiler.Profiler"
+ <bean id="profiler" class="com.xyz.profiler.Profiler"
factory-method="aspectOf">
<property name="profilingStrategy" ref="jamonProfilingStrategy"/>
</bean>
@@ -3039,7 +3039,7 @@ public class Account {
and only beans with names matched by at least one of the patterns will
be used for Spring AOP autoproxy configuration:
- <aop:aspectj-autoproxy>
+ <aop:aspectj-autoproxy>
<aop:include name="thisBean"/>
<aop:include name="thatBean"/>
</aop:aspectj-autoproxy>
@@ -3108,7 +3108,7 @@ public class Account {
quick-and-dirty time-based profiler, using the @AspectJ-style of
aspect declaration.
- package foo;
+ package foo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
@@ -3145,7 +3145,7 @@ public class ProfilingAspect {
classpath called ' META-INF/aop.xml' is standard
AspectJ.
- <!DOCTYPE aspectj PUBLIC
+ <!DOCTYPE aspectj PUBLIC
"-//AspectJ//DTD//EN" "http://www.eclipse.org/aspectj/dtd/aspectj.dtd">
<aspectj>
@@ -3175,7 +3175,7 @@ public class ProfilingAspect {
are some more options that you can specify, but these are detailed
later).
- <?xml version="1.0" encoding="UTF-8"?>
+ <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
@@ -3198,7 +3198,7 @@ http://www.springframework.org/schema/context http://www.springframework.org/sch
main(..) method to demonstrate the LTW in
action.
- package foo;
+ package foo;
import org.springframework.context.support.ClassPathXmlApplicationContext;
@@ -3256,7 +3256,7 @@ ms % Task name
on the Main program will yield the same
result.
- package foo;
+ package foo;
import org.springframework.context.support.ClassPathXmlApplicationContext;
@@ -3400,7 +3400,7 @@ public final class Main {
below a valid <context:load-time-weaver/>
definition that uses default settings.
- <?xml version="1.0" encoding="UTF-8"?>
+ <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
@@ -3493,7 +3493,7 @@ http://www.springframework.org/schema/context http://www.springframework.org/sch
<context:load-time-weaver/> element. Find
below an example of doing just that:
- <?xml version="1.0" encoding="UTF-8"?>
+ <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
@@ -3601,7 +3601,7 @@ http://www.springframework.org/schema/context http://www.springframework.org/sch
included in Tomcat's common lib directory in order to make this
setup work.
- <Context path="/myWebApp" docBase="/my/webApp/location">
+ <Context path="/myWebApp" docBase="/my/webApp/location">
<Loader loaderClass="org.springframework.instrument.classloading.tomcat.TomcatInstrumentableClassLoader"
useSystemClassLoaderAsParent="false"/>
</Context>
diff --git a/spring-framework-reference/src/beans.xml b/spring-framework-reference/src/beans.xml
index cd746acf4c7..ff489acd72b 100644
--- a/spring-framework-reference/src/beans.xml
+++ b/spring-framework-reference/src/beans.xml
@@ -6,31 +6,10 @@
IntroductionThis chapter covers the Spring Framework's implementation of the
- Inversion of Control (IoC)
- See the section entitled
- principle.
-
-
- BeanFactory or
- ApplicationContext?
-
- Users are sometimes unsure whether a
- BeanFactory or an
- ApplicationContext is best suited for use
- in a particular situation. A BeanFactory
- pretty much just instantiates and configures beans. An
- ApplicationContext also does that,
- and it provides the supporting infrastructure to
- enable lots of enterprise-specific features such as
- transactions and AOP.
-
- In short, favor the use of an
- ApplicationContext.
-
- (For the specific details behind this recommendation, see this
- section.)
-
+ Inversion of Control (IoC)
+ See the section entitled
+ principle.
The org.springframework.beans and
org.springframework.context packages provide the basis
@@ -57,6 +36,28 @@
be considered to apply to the
ApplicationContext as well.
+
+ BeanFactory or
+ ApplicationContext?
+
+ Users are sometimes unsure whether a
+ BeanFactory or an
+ ApplicationContext is best suited for use
+ in a particular situation. A BeanFactory
+ pretty much just instantiates and configures beans. An
+ ApplicationContext also does that,
+ and it provides the supporting infrastructure to
+ enable lots of enterprise-specific features such as
+ transactions and AOP.
+
+ In short, favor the use of an
+ ApplicationContext.
+
+ (For the specific details behind this recommendation, see this
+ section.)
+
+
This chapter is divided into two parts, with the first part covering the basic principles
that apply to both the BeanFactory and
@@ -114,21 +115,19 @@
configuration metadata and uses it to create a
fully configured system or application.
-
-
+
-
+
-
+
-
- The Spring IoC container
-
-
-
+
The Spring IoC container
+ Configuration metadata
@@ -156,55 +155,55 @@
You can find details of another form of metadata that the
Spring container can consume in the section entitled
+ linkend="beans-annotation-config" />
-
-
- Resources
+
+ Resources
- 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,
- etc.
+ 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,
+ etc.
- Once you have learned about Spring's IoC container, you may wish
- to learn a little more about Spring's
- Resource abstraction, as described in
- the chapter entitled .
-
+ Once you have learned about Spring's IoC container, you may
+ wish to learn a little more about Spring's
+ Resource abstraction, as described in
+ the chapter entitled .
+
- In the vast majority of 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 J2EE web descriptor XML in the
- web.xml file of the application will typically
- suffice (see ).
-
+ In the vast majority of 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 J2EE web descriptor XML in the
+ web.xml file of the application will typically
+ suffice (see ).
- Spring configuration consists of at least one bean definition that
- the container must manage, but typically there will be more than one bean
- definition. When using XML-based configuration metadata, these beans are
- configured as <bean/> elements inside a top-level
- <beans/> element.
+ Spring configuration consists of at least one bean definition
+ that the container must manage, but typically there will be more than
+ one bean definition. When using XML-based configuration metadata,
+ these beans are configured as <bean/>
+ elements inside a top-level <beans/>
+ element.
- These bean definitions correspond to the actual objects that make up
- your application. Typically you will have bean definitions for your
- service layer objects, your 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/load
- domain objects.
+ These bean definitions correspond to the actual objects that
+ make up your application. Typically you will have bean definitions for
+ your service layer objects, your 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/load domain objects.
- Find below an example of the basic structure of XML-based
- configuration metadata.
+ Find below an example of the basic structure of XML-based
+ configuration metadata.
-
+ Instantiating a container
@@ -251,16 +252,16 @@ BeanFactory factory = context;
load bean definitions from another file (or files). Let's look at a
sample:
- <beans>
+
- <import resource="services.xml"/>
- <import resource="resources/messageSource.xml"/>
- <import resource="/resources/themeSource.xml"/>
+
+
+
- <bean id="bean1" class="..."/>
- <bean id="bean2" class="..."/>
+
+
-</beans>
+]]>In this example, external bean definitions are being loaded from
3 files, services.xml,
@@ -278,26 +279,27 @@ BeanFactory factory = context;
being imported must be valid XML bean definition files according to
the Spring Schema or DTD, including the top level
<beans/> element.
+
+
+ It is possible to reference files in parent directories using
+ a relative "../" path. However, this is not recommended because it
+ creates a dependency on a file that is outside the current
+ application. This is in particular not recommended for "classpath:"
+ URLs (e.g. "classpath:../services.xml") where the runtime resolution
+ process will pick the "nearest" classpath root and then look into
+ its parent directory. This is fragile since classpath configuration
+ changes may lead to a different directory being picked.
+
+ Note that you can always use fully qualified resource
+ locations instead of relative paths: e.g.
+ "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 then. It is generally
+ preferable to keep an indirection for such absolute locations, e.g.
+ through "${...}" placeholders that are resolved against JVM system
+ properties at runtime.
+
-
-
- It is possible to reference files in parent directories using a relative "../"
- path. However, this is not recommended because it creates a dependency on a file
- that is outside the current application. This is in particular not recommended
- for "classpath:" URLs (e.g. "classpath:../services.xml") where the runtime
- resolution process will pick the "nearest" classpath root and then look into
- its parent directory. This is fragile since classpath configuration changes
- may lead to a different directory being picked.
-
- Note that you can always use fully qualified resource locations
- instead of relative paths: e.g. "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 then.
- It is generally preferable to keep an indirection for such absolute
- locations, e.g. through "${...}" placeholders that are resolved
- against JVM system properties at runtime.
-
-
@@ -350,12 +352,14 @@ BeanFactory factory = context;The bean definition
-
-
+
+
+ Feature
+
Explained in...
@@ -363,92 +367,73 @@ BeanFactory factory = context;class
-
-
-
-
-
+
+
+ name
-
-
-
-
-
+
+ scope
-
-
-
-
-
+
+
+ constructor arguments
-
-
-
-
-
+
+
+ properties
-
-
-
-
-
+
+
+ autowiring mode
-
-
-
-
-
+
+
+ dependency checking mode
-
-
-
-
-
+
+
+ lazy-initialization mode
-
-
-
-
-
+
+
+ initialization method
-
-
-
-
-
+
+
+ destruction method
-
-
-
-
-
+
+
+
@@ -531,7 +516,7 @@ BeanFactory factory = context;
XML-based configuration metadata this may be accomplished via the
use of the <alias/> element.
- <alias name="fromName" alias="toName"/>
+ ]]>In this case, a bean in the same container which is named
'fromName', may also after the use of this alias
@@ -547,8 +532,8 @@ BeanFactory factory = context;
easily handled by adding to the MyApp XML fragment the following
standalone aliases:
- <alias name="componentA-dataSource" alias="componentB-dataSource"/>
-<alias name="componentA-dataSource" alias="myApp-dataSource" />
+
+]]>Now each component and the main application can refer to the
dataSource via a name that is unique and guaranteed not to clash
@@ -575,9 +560,7 @@ BeanFactory factory = context;'class' attribute on a bean definition would
be...
-
- com.example.Foo$Bar
-
+ com.example.Foo$BarNotice the use of the $ character in the
name to separate the inner class name from the outer class
@@ -597,8 +580,8 @@ BeanFactory factory = context;
boils down to being a Class property on a
BeanDefinition instance) is normally
mandatory (see and for the two exceptions) and
+ linkend="beans-factory-class-instance-factory-method" /> and for the two exceptions) and
is used for one of two purposes. The class property specifies the
class of the bean to be constructed in the common case where the
container itself directly creates the bean by calling its constructor
@@ -637,9 +620,9 @@ BeanFactory factory = context;When using XML-based configuration metadata you can specify
your bean class like so:
- <bean id="exampleBean" class="examples.ExampleBean"/>
+
-<bean name="anotherExample" class="examples.ExampleBeanTwo"/>
+]]>The mechanism for supplying arguments to the constructor (if
required), or setting properties of the object instance after it has
@@ -669,9 +652,9 @@ BeanFactory factory = context;
this example, the createInstance() method
must be a static method.
- <bean id="exampleBean"
+
+ factory-method="createInstance"/>]]>The mechanism for supplying (optional) arguments to the
factory method, or setting properties of the object instance after
@@ -710,22 +693,21 @@ BeanFactory factory = context;
properties are still to be discussed, one implication of this
approach is that the factory bean itself can be managed and
configured via DI.
-
-
- When the Spring documentation makes mention of a 'factory
- bean', this will be a reference to a bean that is configured in the
- Spring container that will create objects via an instance
- or static
- factory method. When the documentation mentions a
- FactoryBean (notice the
- capitalization) this is a reference to a Spring-specific
- FactoryBean
- .
-
+
+ When the Spring documentation makes mention of a 'factory
+ bean', this will be a reference to a bean that is configured in
+ the Spring container that will create objects via an instance
+ or static
+ factory method. When the documentation mentions a
+ FactoryBean (notice the
+ capitalization) this is a reference to a Spring-specific
+ FactoryBean .
+
+
@@ -740,8 +722,8 @@ BeanFactory factory = context;BeanFactory you would create one and read
in some bean definitions in the XML format as follows:
- Resource res = new FileSystemResource("beans.xml");
-BeanFactory factory = new XmlBeanFactory(res);
+ Basically that is all there is to it. Using
getBean(String) you can retrieve instances of
@@ -846,16 +828,16 @@ public class Foo {
specify the constructor argument indexes and / or types
explicitly.
- <beans>
- <bean name="foo" class="x.y.Foo">
- <constructor-arg>
- <bean class="x.y.Bar"/>
- </constructor-arg>
- <constructor-arg>
- <bean class="x.y.Baz"/>
- </constructor-arg>
- </bean>
-</beans>
+
+
+
+
+
+
+
+
+
+]]>When another bean is referenced, the type is known, and
matching can occur (as was the case with the preceding example).
@@ -888,10 +870,10 @@ public class ExampleBean {
the constructor argument using the 'type'
attribute. For example:
- <bean id="exampleBean" class="examples.ExampleBean">
- <constructor-arg type="int" value="7500000"/>
- <constructor-arg type="java.lang.String" value="42"/>
-</bean>
+
+
+
+]]>
@@ -901,10 +883,10 @@ public class ExampleBean {
explicitly by use of the index attribute. For
example:
- <bean id="exampleBean" class="examples.ExampleBean">
- <constructor-arg index="0" value="7500000"/>
- <constructor-arg index="1" value="42"/>
-</bean>
+
+
+
+]]>As well as solving the ambiguity problem of multiple simple
values, specifying an index also solves the problem of ambiguity
@@ -939,159 +921,162 @@ public class ExampleBean {
// business logic that actually 'uses' the injected MovieFinder is omitted...
}
+
+
+ Constructor- or Setter-based DI?
+
+ The Spring team generally advocates the usage of setter
+ injection, since a large number of constructor arguments can get
+ unwieldy, especially when some properties are optional. The presence
+ of setter methods also makes objects of that class amenable to being
+ re-configured (or re-injected) at some later time (for management
+ via JMX MBeans is a particularly
+ compelling use case).
+
+ Constructor-injection is favored by some purists though (and
+ with good reason). Supplying all of an object's dependencies means
+ that that object is never returned to client (calling) code in a
+ less than totally initialized state. The flip side is that the
+ object becomes less amenable to re-configuration (or
+ re-injection).
+
+ There is no hard and fast rule here. Use whatever type of DI
+ makes the most sense for a particular class; sometimes, when dealing
+ with third party classes to which you do not have the source, the
+ choice will already have been made for you - a legacy class may not
+ expose any setter methods, and so constructor injection will be the
+ only type of DI available to you.
+
+
+ The BeanFactory supports both of
+ these variants for injecting dependencies into beans it manages. (It
+ in fact also supports injecting setter-based dependencies after some
+ dependencies have already been supplied via the constructor approach.)
+ The configuration for the dependencies comes in the form of a
+ BeanDefinition, which is used together
+ with PropertyEditor instances to know
+ how to convert properties from one format to another. However, most
+ users of Spring will not be dealing with these classes directly (that
+ is programmatically), but rather with an XML definition file which
+ will be converted internally into instances of these classes, and used
+ to load an entire Spring IoC container instance.
+
+ Bean dependency resolution generally happens as follows:
+
+
+
+ The BeanFactory is created
+ and initialized with a configuration which describes all the
+ beans. (Most Spring users use a
+ BeanFactory or
+ ApplicationContext implementation
+ that supports XML format configuration files.)
+
+
+
+ Each bean has dependencies expressed in the form of
+ properties, constructor arguments, or arguments to the
+ static-factory method when that is used instead of a normal
+ constructor. These dependencies will be provided to the bean,
+ when the bean is actually created.
+
+
+
+ Each property or constructor argument is either 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 must be
+ able to be converted from whatever format it was specified in, 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, including the validation that properties
+ which are bean references are actually referring to valid beans.
+ However, the bean properties themselves are not set until the bean
+ is actually created. For those beans that are
+ singleton-scoped and set to be pre-instantiated (such as singleton
+ beans in an ApplicationContext),
+ creation happens at the time that the container is created, but
+ otherwise this is only when the bean is requested. When a bean
+ actually has to be created, this will potentially cause a graph of
+ other beans to be created, as its dependencies and its dependencies'
+ dependencies (and so on) are created and assigned.
+
+
+ Circular dependencies
+
+ If you are using predominantly constructor injection it is
+ possible to write and configure your classes and beans such that an
+ unresolvable circular dependency scenario is created.
+
+ Consider the scenario where you have class A, which requires
+ an instance of class B to be provided via constructor injection, and
+ class B, which requires an instance of class A to be provided via
+ constructor injection. If you configure beans for classes A and B to
+ be injected into each other, the Spring IoC container will detect
+ this circular reference at runtime, and throw a
+ BeanCurrentlyInCreationException.
+
+ One possible solution to this issue is to edit the source code
+ of some of your classes to be configured via setters instead of via
+ constructors. Another solution is not to use constructor injection
+ and stick to setter injection only. In other words, while it should
+ generally be avoided in all but the rarest of circumstances, it is
+ possible to configure circular dependencies with setter
+ injection.
+
+ Unlike the typical case (with no circular
+ dependencies), a circular dependency between bean A and bean B will
+ force 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 will
+ detect misconfiguration issues, such as references to non-existent
+ beans and circular dependencies, at container load-time. It will
+ actually set properties and resolve dependencies as late as possible,
+ which is when the bean is actually created. This means that a Spring
+ container which has loaded correctly can later generate an exception
+ when you request a bean if there is a problem creating that bean or
+ one of its dependencies. This could happen if the bean throws an
+ exception as a result of a missing or invalid property, for example.
+ 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 find out about configuration issues when the
+ ApplicationContext is created, not
+ later. If you wish, you can still override this default behavior and
+ set any of these singleton beans to lazy-initialize (that is not be
+ pre-instantiated).
+
+ If no circular dependencies are involved (see sidebar for a
+ discussion of circular dependencies), when one or more collaborating
+ beans are being injected into a dependent bean, each collaborating
+ bean is totally configured prior to being passed
+ (via one of the DI flavors) to the dependent bean. This means that if
+ bean A has a dependency on bean B, the Spring IoC container will
+ totally configure bean B prior to invoking the
+ setter method on bean A; you can read 'totally
+ configure' to mean that the bean will be instantiated (if
+ not a pre-instantiated singleton), all of its dependencies will be
+ set, and the relevant lifecycle methods (such as a configured init
+ method or the IntializingBean
+ callback method) will all be invoked.
-
- Constructor- or Setter-based DI?
-
- The Spring team generally advocates the usage of setter
- injection, since a large number of constructor arguments can get
- unwieldy, especially when some properties are optional. The presence
- of setter methods also makes objects of that class amenable to being
- re-configured (or re-injected) at some later time (for management via
- JMX MBeans is a particularly compelling use
- case).
-
- Constructor-injection is favored by some purists though (and
- with good reason). Supplying all of an object's dependencies means
- that that object is never returned to client (calling) code in a less
- than totally initialized state. The flip side is that the object
- becomes less amenable to re-configuration (or re-injection).
-
- There is no hard and fast rule here. Use whatever type of DI
- makes the most sense for a particular class; sometimes, when dealing
- with third party classes to which you do not have the source, the
- choice will already have been made for you - a legacy class may not
- expose any setter methods, and so constructor injection will be the
- only type of DI available to you.
-
-
- The BeanFactory supports both of
- these variants for injecting dependencies into beans it manages. (It in
- fact also supports injecting setter-based dependencies after some
- dependencies have already been supplied via the constructor approach.)
- The configuration for the dependencies comes in the form of a
- BeanDefinition, which is used together
- with PropertyEditor instances to know how
- to convert properties from one format to another. However, most users of
- Spring will not be dealing with these classes directly (that is
- programmatically), but rather with an XML definition file which will be
- converted internally into instances of these classes, and used to load
- an entire Spring IoC container instance.
-
- Bean dependency resolution generally happens as follows:
-
-
-
- The BeanFactory is created and
- initialized with a configuration which describes all the beans.
- (Most Spring users use a BeanFactory
- or ApplicationContext implementation
- that supports XML format configuration files.)
-
-
-
- Each bean has dependencies expressed in the form of
- properties, constructor arguments, or arguments to the
- static-factory method when that is used instead of a normal
- constructor. These dependencies will be provided to the bean,
- when the bean is actually created.
-
-
-
- Each property or constructor argument is either 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 must be able
- to be converted from whatever format it was specified in, 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, including the validation that properties which
- are bean references are actually referring to valid beans. However, the
- bean properties themselves are not set until the bean is
- actually created. For those beans that are singleton-scoped
- and set to be pre-instantiated (such as singleton beans in an
- ApplicationContext), creation happens at
- the time that the container is created, but otherwise this is only when
- the bean is requested. When a bean actually has to be created, this will
- potentially cause a graph of other beans to be created, as its
- dependencies and its dependencies' dependencies (and so on) are created
- and assigned.
-
-
- Circular dependencies
-
- If you are using predominantly constructor injection it is
- possible to write and configure your classes and beans such that an
- unresolvable circular dependency scenario is created.
-
- Consider the scenario where you have class A, which requires an
- instance of class B to be provided via constructor injection, and
- class B, which requires an instance of class A to be provided via
- constructor injection. If you configure beans for classes A and B to
- be injected into each other, the Spring IoC container will detect this
- circular reference at runtime, and throw a
- BeanCurrentlyInCreationException.
-
- One possible solution to this issue is to edit the source code
- of some of your classes to be configured via setters instead of via
- constructors. Another solution is not to use constructor injection and
- stick to setter injection only. In other words, while it should
- generally be avoided in all but the rarest of circumstances, it is
- possible to configure circular dependencies with setter
- injection.
-
- Unlike the typical case (with no circular
- dependencies), a circular dependency between bean A and bean B will
- force 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 will
- detect misconfiguration issues, such as references to non-existent beans
- and circular dependencies, at container load-time. It will actually set
- properties and resolve dependencies as late as possible, which is when
- the bean is actually created. This means that a Spring container which
- has loaded correctly can later generate an exception when you request a
- bean if there is a problem creating that bean or one of its
- dependencies. This could happen if the bean throws an exception as a
- result of a missing or invalid property, for example. 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 find out about configuration issues when the
- ApplicationContext is created, not later.
- If you wish, you can still override this default behavior and set any of
- these singleton beans to lazy-initialize (that is not be
- pre-instantiated).
-
- If no circular dependencies are involved (see sidebar for a
- discussion of circular dependencies), when one or more collaborating
- beans are being injected into a dependent bean, each collaborating bean
- is totally configured prior to being passed (via
- one of the DI flavors) to the dependent bean. This means that if bean A
- has a dependency on bean B, the Spring IoC container will
- totally configure bean B prior to invoking the
- setter method on bean A; you can read 'totally
- configure' to mean that the bean will be instantiated (if not
- a pre-instantiated singleton), all of its dependencies will be set, and
- the relevant lifecycle methods (such as a configured init
- method or the IntializingBean
- callback method) will all be invoked.
-
Some examples
@@ -1112,7 +1097,7 @@ public class ExampleBean {
<bean id="anotherExampleBean" class="examples.AnotherBean"/>
<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
- public class ExampleBean {
+
+}]]>As you can see, setters have been declared to match against the
properties specified in the XML file. Find below an example of using
@@ -1151,7 +1136,7 @@ public class ExampleBean {
<bean id="anotherExampleBean" class="examples.AnotherBean"/>
<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
- public class ExampleBean {
+
+}]]>As you can see, the constructor arguments specified in the bean
definition will be used to pass in as arguments to the constructor of
@@ -1173,15 +1158,15 @@ public class ExampleBean {
constructor, Spring is told to call a static
factory method to return an instance of the object:
- <bean id="exampleBean" class="examples.ExampleBean"
- factory-method="createInstance">
- <constructor-arg ref="anotherExampleBean"/>
- <constructor-arg ref="yetAnotherBean"/>
- <constructor-arg value="1"/>
-</bean>
+
+
+
+
+
-<bean id="anotherExampleBean" class="examples.AnotherBean"/>
-<bean id="yetAnotherBean" class="examples.YetAnotherBean"/>
+
+]]>public class ExampleBean {
@@ -1308,23 +1293,23 @@ public class ExampleBean {
container (to a <constructor-arg/> or
<property/> element).
- <bean id="theTargetBean" class="..."/>
+
-<bean id="theClientBean" class="...">
- <property name="targetName">
- <idref bean="theTargetBean" />
- </property>
-</bean>
+
+
+
+
+]]>The above bean definition snippet is
exactly equivalent (at runtime) to the
following snippet:
- <bean id="theTargetBean" class="..." />
+
-<bean id="client" class="...">
- <property name="targetName" value="theTargetBean" />
-</bean>
+
+
+]]>The main reason the first form is preferable to the second is
that using the idref tag allows the container to
@@ -1387,7 +1372,7 @@ public class ExampleBean {
bean, or one of the values in the 'name' attribute
of the target bean.
- <ref bean="someBean"/>
+ ]]>Specifying the target bean by using the local
attribute leverages the ability of the XML parser to validate XML id
@@ -1399,7 +1384,7 @@ public class ExampleBean {
about errors as early as possible) if the target bean is in the same
XML file.
- <ref local="someBean"/>
+ ]]>Specifying the target bean by using the
'parent' attribute allows a reference to be created
@@ -1516,16 +1501,18 @@ public class ExampleBean {
</property>
</bean>
- The nested element style used this initial
- example tends to become quite verbose. Fortunately, there are
- attribute shortcuts for most elements, which you can read about in
- .
+
+ The nested element style used this initial example tends to
+ become quite verbose. Fortunately, there are attribute shortcuts for
+ most elements, which you can read about in .
+ Note that the value of a map key or value, or a set
value, can also again be any of the following
elements:
- bean | ref | idref | list | set | map | props | value | null
+ Collection merging
@@ -1585,9 +1572,9 @@ public class ExampleBean {
adminEmails collection with the parent's
adminEmails collection.
- administrator=administrator@example.com
+
+support=support@example.co.uk]]>Notice how the child Properties
collection's value set will have inherited all the property elements
@@ -1642,26 +1629,26 @@ support=support@example.co.uk
instances will be converted to the appropriate type prior to being
added to the Collection.
- public class Foo {
+ accounts;
- public void setAccounts(Map<String, Float> accounts) {
+ public void setAccounts(Map accounts) {
this.accounts = accounts;
}
-}
+}]]>
- <beans>
- <bean id="foo" class="x.y.Foo">
- <property name="accounts">
- <map>
- <entry key="one" value="9.99"/>
- <entry key="two" value="2.75"/>
- <entry key="six" value="3.99"/>
- </map>
- </property>
- </bean>
-</beans>
+
+
+
+
+
+
+]]>When the 'accounts' property of the
'foo' bean is being prepared for injection, the
@@ -1686,18 +1673,18 @@ support=support@example.co.uk
email property being set to the empty String
value ("")
- <bean class="ExampleBean">
- <property name="email"><value/></property>
-</bean>
+
+
+]]>This is equivalent to the following Java code:
exampleBean.setEmail(""). The special
<null> element may be used to indicate a
null value. For example:
- <bean class="ExampleBean">
- <property name="email"><null/></property>
-</bean>
+
+
+]]>The above configuration is equivalent to the following Java
code: exampleBean.setEmail(null).
@@ -1724,25 +1711,25 @@ support=support@example.co.uk
embedding a full <value/> element.
Therefore, the following:
- <property name="myProperty">
- <value>hello</value>
-</property>
+
+ hello
+]]>
- <constructor-arg>
- <value>hello</value>
-</constructor-arg>
+
+ hello
+]]>
- <entry key="myKey">
- <value>hello</value>
-</entry>
+
+ hello
+]]>are equivalent to:
- <property name="myProperty" value="hello"/>
+ ]]>
- <constructor-arg value="hello"/>
+ ]]>
- <entry key="myKey" value="hello"/>
+ ]]>The <property/> and
<constructor-arg/> elements support a
@@ -1750,19 +1737,19 @@ support=support@example.co.uk
used instead of a full nested <ref/>
element. Therefore, the following:
- <property name="myProperty">
- <ref bean="myBean">
-</property>
+
+
+]]>
- <constructor-arg>
- <ref bean="myBean">
-</constructor-arg>
+
+
+]]>... are equivalent to:
- <property name="myProperty" ref="myBean"/>
+ ]]>
- <constructor-arg ref="myBean"/>
+ ]]>Note however that the shortcut form is equivalent to a
<ref bean="xxx"> element; there is no
@@ -1775,16 +1762,16 @@ support=support@example.co.uk'value' / 'value-ref'
attributes. Therefore, the following:
- <entry>
- <key>
- <ref bean="myKeyBean" />
- </key>
- <ref bean="myValueBean" />
-</entry>
+
+
+
+
+
+]]>is equivalent to:
- <entry key-ref="myKeyBean" value-ref="myValueBean"/>
+ ]]>Again, the shortcut form is equivalent to a <ref
bean="xxx"> element; there is no shortcut for
@@ -1818,19 +1805,19 @@ support=support@example.co.uk
the end: the first is using the standard XML format whereas the
second example is using the p-namespace.
- <beans xmlns="http://www.springframework.org/schema/beans"
+
- <bean name="classic" class="com.example.ExampleBean">
- <property name="email" value="foo@bar.com/>
- </bean>
+
+
+
+]]>As you can see, we are including an attribute in the
p-namespace called email in the bean definition - this is telling
@@ -1842,26 +1829,26 @@ support=support@example.co.ukThis next example includes two more bean definitions that both
have a reference to another bean:
- <beans xmlns="http://www.springframework.org/schema/beans"
+
- <bean name="john-classic" class="com.example.Person">
- <property name="name" value="John Doe"/>
- <property name="spouse" ref="jane"/>
- </bean>
+
+
+
+
- <bean name="john-modern"
+
- <bean name="jane" class="com.example.Person">
- <property name="name" value="Jane Doe"/>
- </bean>
-</beans>
+
+
+
+]]>As you can see, this example doesn't only include a property
value using the p-namespace, but also uses a special format to
@@ -1899,9 +1886,9 @@ support=support@example.co.uk
the final property name are not null. Consider the
following bean definition...
- <bean id="foo" class="foo.Bar">
- <property name="fred.bob.sammy" value="123" />
-</bean>
+
+
+]]>The foo bean has a fred
property which has a bob property, which has a
@@ -1943,22 +1930,24 @@ support=support@example.co.uk
'depends-on' attribute, with commas, whitespace and
semicolons all valid delimiters, like so:
- <bean id="beanOne" class="ExampleBean" depends-on="manager,accountDao">
- <property name="manager" ref="manager" />
-</bean>
+
+
+
-<bean id="manager" class="ManagerBean" />
-<bean id="accountDao" class="x.y.jdbc.JdbcAccountDao" />
+
+]]>
- The 'depends-on' attribute at the bean definition
- level is used not only to specify an initialization time dependency, but
- also to specify the corresponding destroy time dependency (in the case of
- singleton beans
- only). Dependent beans that define a 'depends-on'
- relationship with a given bean will be destroyed first - prior to the given
- bean itself being destroyed. As a consequence, 'depends-on'
- may be used to control shutdown order too.
+ The 'depends-on' attribute at the bean
+ definition level is used not only to specify an initialization time
+ dependency, but also to specify the corresponding destroy time
+ dependency (in the case of singleton beans only).
+ Dependent beans that define a 'depends-on'
+ relationship with a given bean will be destroyed first - prior to the
+ given bean itself being destroyed. As a consequence,
+ 'depends-on' may be used to control shutdown order
+ too.
@@ -2039,7 +2028,7 @@ support=support@example.co.uk
need to specify properties or constructor arguments, thus saving a
significant amount of typing. See the section entitled
+ linkend="beans-factory-collaborators" />
When using XML-based configuration metadata, the autowire
mode for a bean definition is specified by using the
autowire attribute of the
@@ -2050,12 +2039,14 @@ support=support@example.co.uk
Autowiring modes
-
-
+
+
+ Mode
+
Explanation
@@ -2201,7 +2192,7 @@ support=support@example.co.uk
Finally, if you are using at least Java 5, you may be interested in
exploring the more fine-grained control available with annotation-based
configuration as described in the section entitled .
+ linkend="beans-annotation-config" />.
When deciding whether to use autowiring, there is no wrong or
right answer in all cases. A degree of consistency across a project is
@@ -2267,8 +2258,9 @@ support=support@example.co.uk
Dependency checking modes
-
-
+
+
+
@@ -2314,7 +2306,7 @@ support=support@example.co.uk
If you are using Java 5 and thus have access to source-level
annotations, you may find the section entitled to be of interest.
+ linkend="metadata-annotations-required" /> to be of interest.
@@ -2550,9 +2542,9 @@ public class ReplacementComputeValue implements MethodReplacer {
fully qualified type name. For example, all the following would match
java.lang.String.
- java.lang.String
+
+ Str]]>Since the number of arguments is often enough to distinguish
between each possible choice, this shortcut can save a lot of typing,
@@ -2600,80 +2592,56 @@ public class ReplacementComputeValue implements MethodReplacer {
-
-
- singleton
-
-
+ singleton
+
-
- Scopes a single bean definition to a single object
- instance per Spring IoC container.
-
+ Scopes a single bean definition to a single object
+ instance per Spring IoC container.
-
-
- prototype
-
-
+ prototype
+
-
- Scopes a single bean definition to any number of object
- instances.
-
+ Scopes a single bean definition to any number of
+ object instances.
-
-
- request
-
-
+ request
+
-
- Scopes a single bean definition to the lifecycle of a
- single HTTP request; that is each and every HTTP request will
- have 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 a
+ single HTTP request; that is each and every HTTP request will have
+ 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.
-
-
- session
-
-
+ session
+
-
- Scopes a single bean definition to the lifecycle of a HTTP
- Session. Only valid in the
- context of a web-aware Spring
- ApplicationContext.
-
+ Scopes a single bean definition to the lifecycle of a
+ HTTP Session. Only valid in the
+ context of a web-aware Spring
+ ApplicationContext.
-
-
- global
- session
-
-
+ global
+ session
-
- 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
+ global HTTP Session. Typically only
+ valid when used in a portlet context. Only valid in the context of
+ a web-aware Spring
+ ApplicationContext.
@@ -2696,19 +2664,17 @@ public class ReplacementComputeValue implements MethodReplacer {
references for that named bean will result in the cached
object being returned.
-
-
+
+ format="PNG" />
+ format="PNG" />
-
-
+ Please be aware that Spring's concept of a singleton bean is quite
different from the Singleton pattern as defined in the seminal Gang of
@@ -2751,19 +2717,17 @@ public class ReplacementComputeValue implements MethodReplacer {
it was just easier for this author to reuse the core of the singleton
diagram.
-
-
+
+ format="PNG" />
+ format="PNG" />
-
-
+ To define a bean as a prototype in XML, you would write
configuration like so:
@@ -2796,7 +2760,7 @@ public class ReplacementComputeValue implements MethodReplacer {
the Java 'new' operator. All lifecycle aspects past
that point have to be handled by the client. (The lifecycle of a bean in
the Spring container is further described in the section entitled .)
+ linkend="beans-factory-lifecycle" />.)
@@ -2822,37 +2786,37 @@ public class ReplacementComputeValue implements MethodReplacer {
in the scenario where you need to get a brand new instance of a
(prototype) bean again and again and again at runtime, you are referred
to the section entitled
+ linkend="beans-factory-method-injection" />
+
+
+ Backwards compatibility note: specifying the lifecycle scope in
+ XML
+
+ If you are referencing the
+ 'spring-beans.dtd' DTD in a bean definition
+ file(s), and you are being explicit about the lifecycle scope of your
+ beans you must use the "singleton" attribute to
+ express the lifecycle scope (remembering that the singleton lifecycle
+ scope is the default). If you are referencing the
+ 'spring-beans-2.0.dtd' DTD or the Spring 2.0 XSD
+ schema, then you will need to use the "scope"
+ attribute (because the "singleton" attribute was
+ removed from the definition of the new DTD and XSD files in favor of
+ the "scope" attribute).
+
+ To be totally clear about this, this means that if you use the
+ "singleton" attribute in an XML bean definition
+ then you must be referencing the
+ 'spring-beans.dtd' DTD in that
+ file. If you are using the "scope"
+ attribute then you must be referencing either the
+ 'spring-beans-2.0.dtd' DTD or the
+ 'spring-beans-2.5.xsd' XSD in that
+ file.
+
-
- Backwards compatibility note: specifying the lifecycle scope in
- XML
-
- If you are referencing the 'spring-beans.dtd'
- DTD in a bean definition file(s), and you are being explicit about the
- lifecycle scope of your beans you must use the
- "singleton" attribute to express the lifecycle scope
- (remembering that the singleton lifecycle
- scope is the default). If you are referencing the
- 'spring-beans-2.0.dtd' DTD or the Spring 2.0 XSD
- schema, then you will need to use the "scope"
- attribute (because the "singleton" attribute was
- removed from the definition of the new DTD and XSD files in favor of the
- "scope" attribute).
-
- To be totally clear about this, this means that if you use the
- "singleton" attribute in an XML bean definition then
- you must be referencing the
- 'spring-beans.dtd' DTD in that
- file. If you are using the "scope"
- attribute then you must be referencing either the
- 'spring-beans-2.0.dtd' DTD or the
- 'spring-beans-2.5.xsd' XSD in that
- file.
-
-
The other scopes
@@ -2907,13 +2871,13 @@ public class ReplacementComputeValue implements MethodReplacer {
the declarations in your web application's
'web.xml' file.
- <web-app>
+
...
- <listener>
- <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
- </listener>
+
+ org.springframework.web.context.request.RequestContextListener
+
...
-</web-app>
+]]>If you are using an older web container (Servlet 2.3), you will
need to use the provided
@@ -2925,18 +2889,18 @@ public class ReplacementComputeValue implements MethodReplacer {
mapping depends on the surrounding web application configuration and
so you will have to change it as appropriate.)
- <web-app>
+
..
- <filter>
- <filter-name>requestContextFilter</filter-name>
- <filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>requestContextFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
+
+ requestContextFilter
+ org.springframework.web.filter.RequestContextFilter
+
+
+ requestContextFilter
+ /*
+
...
-</web-app>
+]]>That's it. DispatcherServlet,
RequestContextListener and
@@ -2952,7 +2916,7 @@ public class ReplacementComputeValue implements MethodReplacer {
Consider the following bean definition:
- <bean id="loginAction" class="com.foo.LoginAction" scope="request"/>
+ ]]>With the above bean definition in place, the Spring container
will create a brand new instance of the
@@ -2974,7 +2938,7 @@ public class ReplacementComputeValue implements MethodReplacer {
Consider the following bean definition:
- <bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>
+ ]]>With the above bean definition in place, the Spring container
will create a brand new instance of the
@@ -3001,7 +2965,7 @@ public class ReplacementComputeValue implements MethodReplacer {
Consider the following bean definition:
- <bean id="userPreferences" class="com.foo.UserPreferences" scope="globalSession"/>
+ ]]>The global session scope is similar to the
standard HTTP Session scope (<!-- a HTTP Session-scoped bean exposed as a proxy -->
<bean id="userPreferences" class="com.foo.UserPreferences" <aop:scoped-proxy/> element into a scoped
bean definition (you may also need the CGLIB library on your classpath
so that the container can effect class-based proxying; you will also
- need to be using ). So, just why do you
+ need to be using ). So, just why do you
need this <aop:scoped-proxy/> element in the
definition of beans scoped at the request,
session, globalSession and
@@ -3093,11 +3058,11 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/
bean definition as it stands is
incomplete):
- <bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>
+
-<bean id="userManager" class="com.foo.UserManager">
- <property name="userPreferences" ref="userPreferences"/>
-</bean>
+
+
+]]>From the above configuration it is evident that the singleton
bean 'userManager' is being injected with a
@@ -3160,14 +3125,16 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/
Choosing the type of proxy createdBy default, when the Spring container is creating a proxy for
- a bean that is marked up with the <aop:scoped-proxy/>
- element, a CGLIB-based class proxy will be created.
- This means that you need to have the CGLIB library on the classpath
- of your application.
+ a bean that is marked up with the
+ <aop:scoped-proxy/> element, a
+ CGLIB-based class proxy will be created. This means that
+ you need to have the CGLIB library on the classpath of your
+ application.
- Note: CGLIB proxies will only intercept public method
- calls! Do not call non-public methods on such a proxy;
- they will not be delegated to the scoped target object.
+ Note: CGLIB proxies will only intercept public
+ method calls! Do not call non-public methods on such a
+ proxy; they will not be delegated to the scoped target
+ object.You can choose to have the Spring container create 'standard'
JDK interface-based proxies for such scoped beans by specifying
@@ -3183,14 +3150,14 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/
<!-- DefaultUserPreferences implements the UserPreferences interface -->
<bean id="userPreferences" class="com.foo.DefaultUserPreferences" scope="session">
- <aop:scoped-proxy proxy-target-class="false"/>
+ <aop:scoped-proxy proxy-target-class="false"/>
</bean>
<bean id="userManager" class="com.foo.UserManager">
<property name="userPreferences" ref="userPreferences"/>
</bean>
- The section entitled may also
+ The section entitled may also
be of some interest with regard to understanding the nuances of
choosing whether class-based or interface-based proxying is right
for you.
@@ -3235,7 +3202,7 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/
of the bean, after having bound it to the session for future
reference).
- Object get(String name, ObjectFactory objectFactory)
+ The second method should remove the object from the underlying
scope. The session scope implementation for example, removes the
@@ -3243,20 +3210,20 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/
returned (you are allowed to return null if the object with the
specified name wasn't found)
- Object remove(String name)
+ The third method is used to register callbacks the scope should
execute when it is destroyed or when the specified object in the scope
is destroyed. Please refer to the Javadoc or a Spring scope
implementation for more information on destruction callbacks.
- void registerDestructionCallback(String name, Runnable destructionCallback)
+ The last method deals with obtaining the conversation identifier
for the underlying scope. This identifier is different for each scope.
For a session for example, this can be the session identifier.
- String getConversationId()
+
@@ -3272,7 +3239,7 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/
BeanFactory implementations that ship
with Spring); this central method is displayed below:
- void registerScope(String scopeName, Scope scope);
+ The first argument to the
registerScope(..) method is the unique name
@@ -3296,7 +3263,8 @@ beanFactory.registerScope("thread", customScope
rules of your custom Scope like
so:
- <bean id="..." class="..." scope="thread"/>
+ <bean id="..." class="..." scope="thread"/>If you have your own custom Scope
implementation(s), you are not just limited to only programmatic
@@ -3313,9 +3281,10 @@ beanFactory.registerScope("thread", customScope
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
- xsi:schemaLocation="
-http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
-http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
+ xsi:schemaLocation="http://www.springframework.org/schema/beans
+ http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/aop
+ http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
@@ -3339,8 +3308,9 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/
</beans>
- Note that, when placing a <aop:scoped-proxy/> in a FactoryBean
- implementation, it is the factory bean itself that is scoped, not the object returned from
+ Note that, when placing a <aop:scoped-proxy/> in a
+ FactoryBean implementation, it is the
+ factory bean itself that is scoped, not the object returned from
getObject().
@@ -3353,8 +3323,8 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/
Lifecycle callbacks
- The Spring Framework provides several callback interfaces to change
- the behavior of your bean in the container; they include
+ The Spring Framework provides several callback interfaces to
+ change the behavior of your bean in the container; they include
InitializingBean and
DisposableBean. Implementing these
interfaces will result in the container calling
@@ -3369,12 +3339,12 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/
doesn't offer out-of-the-box, you can implement a
BeanPostProcessor yourself. More
information about this can be found in the section entitled .
+ linkend="beans-factory-extension" />.
- All the different lifecycle callback interfaces are described below.
- In one of the appendices, you can find diagrams that show how Spring
- manages beans, how those lifecycle features change the nature of your
- beans, and how they are managed.
+ All the different lifecycle callback interfaces are described
+ below. In one of the appendices, you can find diagrams that show how
+ Spring manages beans, how those lifecycle features change the nature of
+ your beans, and how they are managed.Initialization callbacks
@@ -3386,7 +3356,7 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/
InitializingBean interface specifies
exactly one method:
- void afterPropertiesSet() throws Exception;
+ Generally, the use of the
InitializingBean interface can be
@@ -3397,7 +3367,7 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/
'init-method' attribute. For example, the following
definition:
- <bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/>
+ ]]>public class ExampleBean {
@@ -3408,7 +3378,7 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/
...is exactly the same as...
- <bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
+ ]]>public class AnotherExampleBean implements InitializingBean {
@@ -3430,19 +3400,19 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/
DisposableBean interface specifies a
single method:
- void destroy() throws Exception;
+ Generally, the use of the
- DisposableBean callback interface can be
- avoided and is actually discouraged since it unnecessarily couples the
- code to Spring. As an alternative, bean definitions provide support
- for a generic destroy method to be specified. When using XML-based
- configuration metadata this is done via the
+ DisposableBean callback interface can
+ be avoided and is actually discouraged since it unnecessarily couples
+ the code to Spring. As an alternative, bean definitions provide
+ support for a generic destroy method to be specified. When using
+ XML-based configuration metadata this is done via the
'destroy-method' attribute on the
<bean/>. For example, the following
definition:
- <bean id="exampleInitBean" class="examples.ExampleBean" destroy-method="cleanup"/>
+ ]]>public class ExampleBean {
@@ -3453,7 +3423,7 @@ http://www.springframework.org/schema/aop http://www.springframework.org/schema/
...is exactly the same as...
- <bean id="exampleInitBean" class="examples.AnotherExampleBean"/>
+ ]]>public class AnotherExampleBean implements DisposableBean {
@@ -3694,10 +3664,10 @@ public final class Boot {
BeanFactory that created it, when it is
created by that BeanFactory.
- public interface BeanFactoryAware {
+
+}]]>This allows beans to manipulate the
BeanFactory that created them
@@ -3740,7 +3710,7 @@ public final class Boot {
ObjectFactoryCreatingFactoryBean with the name
of the bean that is to be looked up. Let's look at an example:
- package x.y;
+
+}]]>
- package x.y;
+
+}]]>Find below the XML configuration to wire together the above
classes using the
ObjectFactoryCreatingFactoryBean
approach.
- <beans>
- <bean id="newsFeedManager" class="x.y.NewsFeedManager">
- <property name="factory">
- <bean
-class="org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean">
- <property name="targetBeanName">
- <idref local="newsFeed" />
- </property>
- </bean>
- </property>
- </bean>
- <bean id="newsFeed" class="x.y.NewsFeed" scope="prototype">
- <property name="news" value="... that's fit to print!" />
- </bean>
-</beans>
+
+
+
+
+
+
+
+
+
+
+
+
+
+]]>And here is a small driver program to test the fact that new
(prototype) instances of the newsFeed bean are
@@ -3803,7 +3773,7 @@ class="org.springframework.beans.factory.config.ObjectFactoryCreatingFactoryBean
NewsFeedManager's
printNews() method.
- import org.springframework.context.ApplicationContext;
+
+}]]>The output from running the above program will look like so
(results will of course vary on your machine).
- x.y.NewsFeed@1292d26: '... that's fit to print!'
-x.y.NewsFeed@5329c5: '... that's fit to print!'
+ As of Spring 2.5, you can rely upon autowiring of the
BeanFactory as yet another alternative
to implementing the BeanFactoryAware
interface. The "traditional" constructor and
byType autowiring modes (as described in the
- section entitled ) are now
+ section entitled ) are now
capable of providing a dependency of type
BeanFactory for either a constructor
argument or setter method parameter respectively. For more flexibility
@@ -3841,7 +3811,7 @@ x.y.NewsFeed@5329c5: '... that's fit to print!'
long as the field, constructor, or method in question carries the
@Autowired annotation. For more
information, see the section entitled .
+ linkend="beans-autowired-annotation" />.
@@ -4008,7 +3978,7 @@ x.y.NewsFeed@5329c5: '... that's fit to print!'
recipe that defines the bean), then you rather need to use a
BeanFactoryPostProcessor (described
below in the section entitled .
+ linkend="beans-factory-extension-factory-postprocessors" />.
Also, BeanPostProcessors are scoped
per-container. This is only relevant if you are
@@ -4136,9 +4106,10 @@ public class InstantiationTracingBeanPostProcessor implements BeanPostProcessor
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:lang="http://www.springframework.org/schema/lang"
- xsi:schemaLocation="
-http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
-http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd">
+ xsi:schemaLocation="http://www.springframework.org/schema/beans
+ http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/lang
+ http://www.springframework.org/schema/lang/spring-lang-3.0.xsd">
<lang:groovy id="messenger"
script-source="classpath:org/springframework/scripting/groovy/Messenger.groovy">
@@ -4159,12 +4130,12 @@ http://www.springframework.org/schema/lang http://www.springframework.org/schema
be dependency injected just like any other bean. (The above
configuration also just so happens to define a bean that is backed by
a Groovy script. The Spring 2.0 dynamic language support is detailed
- in the chapter entitled .)
+ in the chapter entitled .)
Find below a small driver script to exercise the above code and
configuration;
- import org.springframework.context.ApplicationContext;
+
+}]]>The output of executing the above program will be (something
like) this:
- Bean 'messenger' created : org.springframework.scripting.groovy.GroovyMessenger@272961
-org.springframework.scripting.groovy.GroovyMessenger@272961
+
@@ -4192,7 +4163,7 @@ org.springframework.scripting.groovy.GroovyMessenger@272961
custom BeanPostProcessor implementation
is a common means of extending the Spring IoC container. This next
example is a bit of a cop-out, in that you are directed to the section
- entitled which
+ entitled which
demonstrates the usage of a custom
BeanPostProcessor implementation that
ships with the Spring distribution which ensures that JavaBean
@@ -4209,11 +4180,12 @@ org.springframework.scripting.groovy.GroovyMessenger@272961
org.springframework.beans.factory.config.BeanFactoryPostProcessor.
The semantics of this interface are similar to the
BeanPostProcessor, with one major
- difference: BeanFactoryPostProcessors operate on the bean
- configuration metadata; that is, the Spring IoC container will allow
- BeanFactoryPostProcessors to read the configuration
- metadata and potentially change it before the
- container has actually instantiated any other beans.
+ difference: BeanFactoryPostProcessors operate on the
+ bean configuration metadata; that is, the Spring
+ IoC container will allow BeanFactoryPostProcessors to
+ read the configuration metadata and potentially change it
+ before the container has actually instantiated any
+ other beans.
You can configure multiple
BeanFactoryPostProcessors if you wish. You can
@@ -4235,7 +4207,7 @@ org.springframework.scripting.groovy.GroovyMessenger@272961
configuration metadata), then you rather need to use a
BeanPostProcessor (described above in
the section entitled .
+ linkend="beans-factory-extension-bpp" />.
Also, BeanFactoryPostProcessors are scoped
per-container. This is only relevant if you are
@@ -4253,10 +4225,12 @@ org.springframework.scripting.groovy.GroovyMessenger@272961
case of an ApplicationContext) to apply
changes of some sort to the configuration metadata that defines a
container. Spring includes a number of pre-existing bean factory
- post-processors, such as PropertyOverrideConfigurer
- and PropertyPlaceholderConfigurer, both described
+ post-processors, such as
+ PropertyOverrideConfigurer and
+ PropertyPlaceholderConfigurer, both described
below. A custom BeanFactoryPostProcessor
- can also be used to register custom property editors, for example.
+ can also be used to register custom property editors, for
+ example.
In a BeanFactory, the process of
applying a BeanFactoryPostProcessor is
@@ -4279,7 +4253,7 @@ cfg.postProcessBeanFactory(factory);
especially when using
BeanFactoryPostProcessors.
-
+ An ApplicationContext will detect
any beans which are deployed into it which implement the
@@ -4339,17 +4313,18 @@ cfg.postProcessBeanFactory(factory);
The actual values come from another file in the standard Java
Properties format:
- jdbc.driverClassName=org.hsqldb.jdbcDriver
+
+jdbc.password=root]]>With the context namespace introduced in
Spring 2.5, it is possible to configure property placeholders with a
- dedicated configuration element. Multiple locations may be provided as a
- comma-separated list for the location attribute.
+ dedicated configuration element. Multiple locations may be provided as
+ a comma-separated list for the location
+ attribute.
- <context:property-placeholder location="classpath:com/foo/jdbc.properties"/>
+ ]]>The PropertyPlaceholderConfigurer doesn't
only look for properties in the Properties file
@@ -4372,16 +4347,16 @@ jdbc.password=root
you have to pick a particular implementation class at runtime. For
example:
- <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <property name="locations">
- <value>classpath:com/foo/strategy.properties</value>
- </property>
- <property name="properties">
- <value>custom.strategy.class=com.foo.DefaultStrategy</value>
- </property>
-</bean>
+
+
+ classpath:com/foo/strategy.properties
+
+
+ custom.strategy.class=com.foo.DefaultStrategy
+
+
-<bean id="serviceStrategy" class="${custom.strategy.class}"/>
+]]>If the class is unable to be resolved at runtime to a valid
class, resolution of the bean will fail once it is about to be
@@ -4415,12 +4390,12 @@ jdbc.password=root
Properties file configuration lines are expected to be in the
format:
- beanName.property=value
+ An example properties file might look like this:
- dataSource.driverClassName=com.mysql.jdbc.Driver
-dataSource.url=jdbc:mysql:mydb
+ This example file would be usable against a container definition
which contains a bean called dataSource, which
@@ -4432,7 +4407,7 @@ dataSource.url=jdbc:mysql:mydb
is already non-null (presumably initialized by the constructors). In
this example...
- foo.fred.bob.sammy=123
+ ... the sammy property of the
bob property of the fred
@@ -4448,8 +4423,7 @@ dataSource.url=jdbc:mysql:mydb
Spring 2.5, it is possible to configure property overriding with a
dedicated configuration element:
- <context:property-override location="classpath:override.properties"/>
-
+ ]]>
@@ -4610,13 +4584,17 @@ dataSource.url=jdbc:mysql:mydb
Feature Matrix
-
+ Feature
- BeanFactory
- ApplicationContext
+
+ BeanFactory
+
+ ApplicationContext
@@ -4725,8 +4703,8 @@ dataSource.url=jdbc:mysql:mydb
has a parent containing a bean with the same name. If so, it uses that
bean as the MessageSource. If it can't
find any source for messages, an empty
- DelegatingMessageSource will be instantiated
- in order to be able to accept calls to the methods defined above.
+ DelegatingMessageSource will be instantiated in
+ order to be able to accept calls to the methods defined above.
Spring currently provides two
MessageSource implementations. These are
@@ -4738,18 +4716,18 @@ dataSource.url=jdbc:mysql:mydb
source. The ResourceBundleMessageSource is more
interesting and is the one we will provide an example for:
- <beans>
- <bean id="messageSource"
- class="org.springframework.context.support.ResourceBundleMessageSource">
- <property name="basenames">
- <list>
- <value>format</value>
- <value>exceptions</value>
- <value>windows</value>
- </list>
- </property>
- </bean>
-</beans>
+
+
+
+
+ format
+ exceptions
+ windows
+
+
+
+]]>This assumes you have three resource bundles defined on your
classpath called format,
@@ -4772,15 +4750,15 @@ argument.required=The '{0}' argument is required.
implementations and so can be cast to the
MessageSource interface.
- public static void main(String[] args) {
+
+}]]>The resulting output from the above program will be...
- Alligators rock!
+ So to summarize, the MessageSource is
defined in a file called 'beans.xml' (this file
@@ -4812,7 +4790,7 @@ argument.required=The '{0}' argument is required.
</beans>
- public class Example {
+
System.out.println(message);
}
-}
+}]]>The resulting output from the invocation of the
execute() method will be...
- The 'userDao' argument is required.
+ With regard to internationalization (i18n), Spring's various
MessageResource implementations follow the same
@@ -4851,17 +4829,17 @@ argument.required=The '{0}' argument is required.
# in 'exceptions_en_GB.properties'
argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
- public static void main(final String[] args) {
+
+}]]>The resulting output from the running of the above program will
be...
- Ebagum lad, the 'userDao' argument is required, I say, required.
+ The MessageSourceAware interface can also
be used to acquire a reference to any
@@ -4872,14 +4850,18 @@ argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
MessageSource when it (the bean) is being created
and configured.
- Note: As an alternative to ResourceBundleMessageSource,
- Spring also provides a ReloadableResourceBundleMessageSource class.
- This variant supports the same bundle file format but is more flexible than the standard
- JDK based ResourceBundleMessageSource implementation.
- In particular, it allows for reading files from any Spring resource location
- (not just from the classpath) and supports hot reloading of bundle property files
- (while efficiently caching them in between). Check out the
- ReloadableResourceBundleMessageSource javadoc for details.
+ Note: As an alternative to
+ ResourceBundleMessageSource, Spring also provides
+ a ReloadableResourceBundleMessageSource class.
+ This variant supports the same bundle file format but is more flexible
+ than the standard JDK based
+ ResourceBundleMessageSource
+ implementation. In particular, it allows for reading files
+ from any Spring resource location (not just from the classpath) and
+ supports hot reloading of bundle property files (while efficiently
+ caching them in between). Check out the
+ ReloadableResourceBundleMessageSource javadoc for
+ details.
@@ -4901,12 +4883,14 @@ argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
Built-in Events
-
-
+
+
+ Event
+
Explanation
@@ -4914,6 +4898,7 @@ argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
ContextRefreshedEvent
+
Published when the
ApplicationContext is initialized
or refreshed, e.g. using the refresh()
@@ -4923,59 +4908,63 @@ argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
post-processor beans are detected and activated, singletons are
pre-instantiated, and the
ApplicationContext object is
- ready for use. A refresh may be triggered multiple times,
- as long as the context hasn't been closed - provided that
- the chosen ApplicationContext
+ ready for use. A refresh may be triggered multiple times, as
+ long as the context hasn't been closed - provided that the
+ chosen ApplicationContext
actually supports such "hot" refreshes (which e.g.
XmlWebApplicationContext does but
- GenericApplicationContext doesn't).
+ GenericApplicationContext
+ doesn't).
ContextStartedEvent
+
Published when the
ApplicationContext is started,
using the start() method on the
ConfigurableApplicationContext
interface. "Started" here means that all
- Lifecycle beans will receive
- an explicit start signal. This will typically be used for
- restarting after an explicit stop, but may also be used
- for starting components that haven't been configured for
- autostart (e.g. haven't started on initialization already).
+ Lifecycle beans will receive an
+ explicit start signal. This will typically be used for
+ restarting after an explicit stop, but may also be used for
+ starting components that haven't been configured for autostart
+ (e.g. haven't started on initialization already).
ContextStoppedEvent
+
Published when the
ApplicationContext is stopped,
using the stop() method on the
ConfigurableApplicationContext
interface. "Stopped" here means that all
- Lifecycle beans will receive
- an explicit stop signal. A stopped context may be restarted
- through a start() call.
+ Lifecycle beans will receive an
+ explicit stop signal. A stopped context may be restarted through
+ a start() call.
ContextClosedEvent
+
Published when the
ApplicationContext is closed,
using the close() method on the
ConfigurableApplicationContext
- interface. "Closed" here means that all singleton beans
- are destroyed. A closed context has reached its end of life;
- it cannot be refreshed or restarted.
+ interface. "Closed" here means that all singleton beans are
+ destroyed. A closed context has reached its end of life; it
+ cannot be refreshed or restarted.
RequestHandledEvent
- A web-specific event telling all beans that an
- HTTP request has been serviced (this will be published
- after the request has been finished).
- Note that this event is only applicable for web applications
- using Spring's
- DispatcherServlet.
+
+ A web-specific event telling all beans that an HTTP
+ request has been serviced (this will be published
+ after the request has been finished). Note
+ that this event is only applicable for web applications using
+ Spring's DispatcherServlet.
@@ -4997,19 +4986,19 @@ argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
Let's look at an example. First, the
ApplicationContext:
- <bean id="emailer" class="example.EmailBean">
- <property name="blackList">
- <list>
- <value>black@list.org</value>
- <value>white@list.org</value>
- <value>john@doe.org</value>
- </list>
- </property>
-</bean>
+
+
+
+ black@list.org
+ white@list.org
+ john@doe.org
+
+
+
-<bean id="blackListListener" class="example.BlackListNotifier">
- <property name="notificationAddress" value="spam@list.org"/>
-</bean>
+
+
+]]>Now, let's look at the actual classes:
@@ -5062,7 +5051,7 @@ argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
For optimal usage and understanding of application contexts, users
should generally familiarize themselves with Spring's
Resource abstraction, as described in the
- chapter entitled .
+ chapter entitled .An application context is a
ResourceLoader, able to be used to load
@@ -5241,55 +5230,57 @@ argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
Deploying a Spring ApplicationContext as a J2EE RAR file
- Since Spring 2.5, it is possible to deploy a Spring ApplicationContext
- as a RAR file, encapsulating the context and all of its required bean classes
- and library JARs in a J2EE RAR deployment unit. This is the equivalent of
- bootstrapping a standalone ApplicationContext, just hosted in J2EE environment,
- being able to access the J2EE server's facilities. RAR deployment is intended
- as a more 'natural' alternative to the not uncommon scenario of deploying a
- headless WAR file - i.e. a WAR file without any HTTP entry points, just used
- for bootstrapping a Spring ApplicationContext in a J2EE environment.
+ Since Spring 2.5, it is possible to deploy a Spring
+ ApplicationContext as a RAR file, encapsulating the context and all of its
+ required bean classes and library JARs in a J2EE RAR deployment unit. This
+ is the equivalent of bootstrapping a standalone ApplicationContext, just
+ hosted in J2EE environment, being able to access the J2EE server's
+ facilities. RAR deployment is intended as a more 'natural' alternative to
+ the not uncommon scenario of deploying a headless WAR file - i.e. a WAR
+ file without any HTTP entry points, just used for bootstrapping a Spring
+ ApplicationContext in a J2EE environment.
- RAR deployment is ideal for application contexts that do not need any
- HTTP entry points but rather just consist of message endpoints and scheduled
- jobs etc. Beans in such a context may use application server resources such
- as the JTA transaction manager and JNDI-bound JDBC DataSources and JMS
- ConnectionFactory instances, and may also register with the platform's
- JMX server - all through Spring's standard transaction management and
- JNDI and JMX support facilities. Application components may also interact
- with the application's server JCA WorkManager through Spring's
- TaskExecutor abstraction.
+ RAR deployment is ideal for application contexts that do not need
+ any HTTP entry points but rather just consist of message endpoints and
+ scheduled jobs etc. Beans in such a context may use application server
+ resources such as the JTA transaction manager and JNDI-bound JDBC
+ DataSources and JMS ConnectionFactory instances, and may also register
+ with the platform's JMX server - all through Spring's standard transaction
+ management and JNDI and JMX support facilities. Application components may
+ also interact with the application's server JCA WorkManager through
+ Spring's TaskExecutor abstraction.
- Check out the JavaDoc of the
- Check out the JavaDoc of the SpringContextResourceAdapter
class for the configuration details involved in RAR deployment.
- For simple deployment needs, all you need to do is the following:
- Package all application classes into a RAR file (which is just a standard
- JAR file with a different file extension), add all required library jars
- into the root of the RAR archive, add a "META-INF/ra.xml" deployment descriptor
- (as shown in SpringContextResourceAdapter's JavaDoc)
- as well as the corresponding Spring XML bean definition file(s)
- (typically "META-INF/applicationContext.xml"), and drop the resulting RAR
- file into your application server's deployment directory!
+ For simple deployment needs, all you need to do is the
+ following: Package all application classes into a RAR file
+ (which is just a standard JAR file with a different file extension), add
+ all required library jars into the root of the RAR archive, add a
+ "META-INF/ra.xml" deployment descriptor (as shown in
+ SpringContextResourceAdapter's JavaDoc) as well as
+ the corresponding Spring XML bean definition file(s) (typically
+ "META-INF/applicationContext.xml"), and drop the resulting RAR file into
+ your application server's deployment directory!
- NOTE: Such RAR deployment units are usually self-contained;
- they do not expose components to the 'outside' world, not even to other
- modules of the same application. Interaction with a RAR-based ApplicationContext
- usually happens through JMS destinations that it shares with other modules.
- A RAR-based ApplicationContext may also - for example - schedule some jobs,
- reacting to new files in the file system (or the like). If it actually needs
- to allow for synchronous access from the outside, it could for example export
- RMI endpoints, which of course may be used by other application modules
- on the same machine as well.
+ NOTE: Such RAR deployment units are usually
+ self-contained; they do not expose components to the 'outside' world, not
+ even to other modules of the same application. Interaction with a
+ RAR-based ApplicationContext usually happens through JMS destinations that
+ it shares with other modules. A RAR-based ApplicationContext may also -
+ for example - schedule some jobs, reacting to new files in the file system
+ (or the like). If it actually needs to allow for synchronous access from
+ the outside, it could for example export RMI endpoints, which of course
+ may be used by other application modules on the same machine as
+ well.Annotation-based configurationAs mentioned in the section entitled , using a
+ linkend="beans-factory-extension-bpp-examples-rabpp" />, using a
BeanPostProcessor in conjunction with
annotations is a common means of extending the Spring IoC container. For
example, Spring 2.0 introduced the possibility of enforcing required
@@ -5298,7 +5289,7 @@ argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
Spring 2.5, it is now possible to follow that same general approach to
drive Spring's dependency injection. Essentially, the
@Autowired annotation provides the same
- capabilities as described in but
+ capabilities as described in but
with more fine-grained control and wider applicability. Spring 2.5 also
adds support for JSR-250 annotations such as
@Resource,
@@ -5318,9 +5309,9 @@ argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
+ http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-2.5.xsd">
+ http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
@@ -5336,19 +5327,22 @@ argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
url="http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/beans/factory/annotation/RequiredAnnotationBeanPostProcessor.html">RequiredAnnotationBeanPostProcessor.)
- Note that <context:annotation-config/> only looks for
- annotations on beans in the same application context it is defined in.
- This means that, if you put <context:annotation-config/> in a
- WebApplicationContext for a DispatcherServlet, it only
- checks for @Autowired beans in your controllers, and not your services.
- See for more information.
+ Note that <context:annotation-config/>
+ only looks for annotations on beans in the same application context it
+ is defined in. This means that, if you put
+ <context:annotation-config/> in a
+ WebApplicationContext for a
+ DispatcherServlet, it only checks for
+ @Autowired beans in your controllers, and
+ not your services. See for more
+ information.@Required
- The @Required annotation applies
- to bean property setter methods, as in the following example:
+ The @Required annotation applies to
+ bean property setter methods, as in the following example:public class SimpleMovieLister {
@@ -5362,14 +5356,16 @@ argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
// ...
}
- This annotation simply indicates that the affected bean property must
- be populated at configuration time: either through an explicit property value
- in a bean definition or through autowiring. The container will throw an exception
- if the affected bean property has not been populated; this allows for eager and
- explicit failure, avoiding NullPointerExceptions or the
- like later on. Note that it is still recommended to put assertions into the
- bean class itself (for example into an init method) in order to enforce those
- required references and values even when using the class outside of a container.
+ This annotation simply indicates that the affected bean property
+ must be populated at configuration time: either through an explicit
+ property value in a bean definition or through autowiring. The container
+ will throw an exception if the affected bean property has not been
+ populated; this allows for eager and explicit failure, avoiding
+ NullPointerExceptions or the like later on. Note
+ that it is still recommended to put assertions into the bean class
+ itself (for example into an init method) in order to enforce those
+ required references and values even when using the class outside of a
+ container.
@@ -5491,28 +5487,31 @@ argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
Only one annotated constructor per-class
- may be marked as required, but multiple non-required
- constructors can be annotated. In that case, each will be considered
- among the candidates and Spring will use the greediest
- constructor whose dependencies can be satisfied.
+ may be marked as required, but multiple
+ non-required constructors can be annotated. In that case, each will be
+ considered among the candidates and Spring will use the
+ greediest constructor whose dependencies can be
+ satisfied.Prefer the use of @Autowired's
- required attribute over the @Required
- annotation. The required attribute indicates that
- the property is not required for autowiring purposes, simply skipping
- it if it cannot be autowired. @Required,
- on the other hand, is stronger in that it enforces the property to
- have been set in any of the container's supported ways; if no value
- has been injected, a corresponding exception will be raised.
+ required attribute over the
+ @Required annotation. The
+ required attribute indicates that the property is
+ not required for autowiring purposes, simply skipping it if it cannot
+ be autowired. @Required, on the other
+ hand, is stronger in that it enforces the property to have been set in
+ any of the container's supported ways; if no value has been injected,
+ a corresponding exception will be raised.
@Autowired may also be used for
- well-known "resolvable dependencies": the BeanFactory
- interface, the ApplicationContext interface,
- the ResourceLoader interface,
- the ApplicationEventPublisher interface
- and the MessageSource interface.
- These interfaces (and their extended interfaces such as
+ well-known "resolvable dependencies": the
+ BeanFactory interface, the
+ ApplicationContext interface, the
+ ResourceLoader interface, the
+ ApplicationEventPublisher interface and
+ the MessageSource interface. These
+ interfaces (and their extended interfaces such as
ConfigurableApplicationContext or
ResourcePatternResolver) will be
automatically resolved, with no special setup necessary.
@@ -5536,9 +5535,9 @@ argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
often necessary to have more control over the selection process. One way
to accomplish this is with Spring's
@Qualifier annotation. This allows for
- associating qualifier values with specific arguments, narrowing the
- set of type matches so that a specific bean is chosen for each argument.
- In the simplest case, this can be a plain descriptive value:
+ associating qualifier values with specific arguments, narrowing the set
+ of type matches so that a specific bean is chosen for each argument. In
+ the simplest case, this can be a plain descriptive value:
public class MovieRecommender {
@@ -5568,17 +5567,18 @@ argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
// ...
}
- The corresponding bean definitions would look like as follows.
- The bean with qualifier value "main" would be wired with the
- constructor argument that has been qualified with the same value.
+ The corresponding bean definitions would look like as follows. The
+ bean with qualifier value "main" would be wired with the constructor
+ argument that has been qualified with the same value.<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
+ xsi:schemaLocation="http://www.springframework.org/schema/beans
+ http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/context
+ http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
@@ -5597,54 +5597,55 @@ argument.required=Ebagum lad, the '{0}' argument is required, I say, required.
</beans>
- For a fallback match, the bean name is considered as a default qualifier
- value. This means that the bean may be defined with an id "main" instead of
- the nested qualifier element, leading to the same matching result. However,
- note that while this can be used to refer to specific beans by name,
- @Autowired is fundamentally about type-driven
- injection with optional semantic qualifiers. This means that qualifier values,
- even when using the bean name fallback, always have narrowing semantics within
- the set of type matches; they do not semantically express a reference to a
- unique bean id. Good qualifier values would be "main" or "EMEA" or "persistent",
- expressing characteristics of a specific component - independent from the bean
- id (which may be auto-generated in case of an anonymous bean definition like
- the one above).
+ For a fallback match, the bean name is considered as a default
+ qualifier value. This means that the bean may be defined with an id
+ "main" instead of the nested qualifier element, leading to the same
+ matching result. However, note that while this can be used to refer to
+ specific beans by name, @Autowired is
+ fundamentally about type-driven injection with optional semantic
+ qualifiers. This means that qualifier values, even when using the bean
+ name fallback, always have narrowing semantics within the set of type
+ matches; they do not semantically express a reference to a unique bean
+ id. Good qualifier values would be "main" or "EMEA" or "persistent",
+ expressing characteristics of a specific component - independent from
+ the bean id (which may be auto-generated in case of an anonymous bean
+ definition like the one above).Qualifiers also apply to typed collections (as discussed above):
- e.g. to Set<MovieCatalog>. In such a case,
- all matching beans according to the declared qualifiers are going to
- be injected as a collection. This implies that qualifiers do not have
- to be unique; they rather simply constitute filtering criteria.
- For example, there could be multiple MovieCatalog
- beans defined with the same qualifier value "action"; all of which
- would be injected into a Set<MovieCatalog>
- annotated with @Qualifier("action").
+ e.g. to Set<MovieCatalog>. In such a case, all
+ matching beans according to the declared qualifiers are going to be
+ injected as a collection. This implies that qualifiers do not have to be
+ unique; they rather simply constitute filtering criteria. For example,
+ there could be multiple MovieCatalog beans
+ defined with the same qualifier value "action"; all of which would be
+ injected into a Set<MovieCatalog> annotated
+ with @Qualifier("action").
- If you intend to express annotation-driven injection by name,
- do not primarily use @Autowired -
- even if is technically capable of referring to a bean name through
- @Qualifier values. Instead,
- prefer the JSR-250 @Resource
- annotation which is semantically defined to identify a specific
- target component by its unique name, with the declared type
- being irrelevant for the matching process.
+ If you intend to express annotation-driven injection by name, do
+ not primarily use @Autowired - even if
+ is technically capable of referring to a bean name through
+ @Qualifier values. Instead, prefer the
+ JSR-250 @Resource annotation which is
+ semantically defined to identify a specific target component by its
+ unique name, with the declared type being irrelevant for the matching
+ process.
- As a specific consequence of this semantic difference,
- beans which are themselves defined as a collection or map type
- cannot be injected via @Autowired
- since type matching is not properly applicable to them.
- Use @Resource for such beans,
- referring to the specific collection/map bean by unique name.
+ As a specific consequence of this semantic difference, beans
+ which are themselves defined as a collection or map type cannot be
+ injected via @Autowired since type
+ matching is not properly applicable to them. Use
+ @Resource for such beans, referring to
+ the specific collection/map bean by unique name.Note: In contrast to
@Autowired which is applicable to
fields, constructors and multi-argument methods (allowing for
narrowing through qualifier annotations at the parameter level),
- @Resource is only supported for
- fields and bean property setter methods with a single argument.
- As a consequence, stick with qualifiers if your injection target
- is a constructor or a multi-argument method.
+ @Resource is only supported for fields
+ and bean property setter methods with a single argument. As a
+ consequence, stick with qualifiers if your injection target is a
+ constructor or a multi-argument method.
You may create your own custom qualifier annotations as well.
@@ -5693,9 +5694,10 @@ public @interface Genre {
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
+ xsi:schemaLocation="http://www.springframework.org/schema/beans
+ http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/context
+ http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
@@ -5714,10 +5716,10 @@ public @interface Genre {
</beans>
- In the next section, entitled ,
- you will see an annotation-based alternative to providing the qualifier
- metadata in XML. Specifically, see: .
-
+ In the next section, entitled , you will see an annotation-based
+ alternative to providing the qualifier metadata in XML. Specifically,
+ see: .In some cases, it may be sufficient to use an annotation without a
value. This may be useful when the annotation serves a more generic
@@ -5727,12 +5729,12 @@ public @interface Genre {
Internet connection is available. First define the simple
annotation:
- @Target({ElementType.FIELD, ElementType.PARAMETER})
+
+}]]>Then add the annotation to the field or property to be
autowired:
@@ -5762,7 +5764,7 @@ public @interface Offline {
be considered an autowire candidate. As an example, consider the
following annotation definition:
- @Target({ElementType.FIELD, ElementType.PARAMETER})
+
+}]]>In this case Format is an enum:
- public enum Format {
+
+}]]>The fields to be autowired are annotated with the custom qualifier
and include values for both attributes: 'genre' and
@@ -5817,9 +5819,10 @@ public @interface MovieQualifier {
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
+ xsi:schemaLocation="http://www.springframework.org/schema/beans
+ http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
+ http://www.springframework.org/schema/context
+ http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
@@ -5865,13 +5868,13 @@ public @interface MovieQualifier {
even if they are not themselves annotated with Spring's
@Qualifier annotation.
- <bean id="customAutowireConfigurer" class="org.springframework.beans.factory.annotation.CustomAutowireConfigurer">
- <property name="customQualifierTypes">
- <set>
- <value>example.CustomQualifier</value>
- </set>
- </property>
-</bean>
+
+
+
+ example.CustomQualifier
+
+
+]]>Note that the particular implementation of
AutowireCandidateResolver that will be
@@ -5898,10 +5901,10 @@ public @interface MovieQualifier {
@ResourceSpring also supports injection using the JSR-250
- @Resource annotation on fields or
- bean property setter methods. This is a common pattern found in
- Java EE 5 and Java 6 (e.g. in JSF 1.2 managed beans or JAX-WS 2.0
- endpoints), which Spring supports for Spring-managed objects as well.
+ @Resource annotation on fields or bean
+ property setter methods. This is a common pattern found in Java EE 5 and
+ Java 6 (e.g. in JSF 1.2 managed beans or JAX-WS 2.0 endpoints), which
+ Spring supports for Spring-managed objects as well.@Resource takes a 'name' attribute,
and by default Spring will interpret that value as the bean name to be
@@ -5918,12 +5921,12 @@ public @interface MovieQualifier {
}
}
- If no name is specified explicitly, then the default name
- will be derived from the name of the field or setter method:
- In case of a field, it will simply be equivalent to the field name;
- in case of a setter method, it will be equivalent to the bean
- property name. So the following example is going to have the bean
- with name "movieFinder" injected into its setter method:
+ If no name is specified explicitly, then the default name will be
+ derived from the name of the field or setter method: In case of a field,
+ it will simply be equivalent to the field name; in case of a setter
+ method, it will be equivalent to the bean property name. So the
+ following example is going to have the bean with name "movieFinder"
+ injected into its setter method:public class SimpleMovieLister {
@@ -5947,22 +5950,24 @@ public @interface MovieQualifier {
Similar to @Autowired,
- @Resource may fall back to standard bean type
- matches (i.e. find a primary type match instead of a specific named bean)
- as well as resolve well-known "resolvable dependencies":
- the BeanFactory interface,
- the ApplicationContext interface,
- the ResourceLoader interface,
- the ApplicationEventPublisher interface
- and the MessageSource interface.
- Note that this only applies to @Resource
- usage with no explicit name specified!
+ @Resource may fall back to standard bean
+ type matches (i.e. find a primary type match instead of a specific named
+ bean) as well as resolve well-known "resolvable dependencies": the
+ BeanFactory interface, the
+ ApplicationContext interface, the
+ ResourceLoader interface, the
+ ApplicationEventPublisher interface and
+ the MessageSource interface. Note that
+ this only applies to @Resource usage with
+ no explicit name specified!
- So the following example will have its customerPreferenceDao
- field looking for a bean with name "customerPreferenceDao" first, then falling
- back to a primary type match for the type CustomerPreferenceDao.
- The "context" field will simply be injected based on the known resolvable dependency
- type ApplicationContext.
+ So the following example will have its
+ customerPreferenceDao field looking for a bean with
+ name "customerPreferenceDao" first, then falling back to a primary type
+ match for the type CustomerPreferenceDao. The
+ "context" field will simply be injected based on the known resolvable
+ dependency type
+ ApplicationContext.public class MovieRecommender {
@@ -6016,7 +6021,7 @@ public @interface MovieQualifier {
For details regarding the effects of combining various lifecycle
mechanisms, see .
+ linkend="beans-factory-lifecycle-combined-effects" />.
@@ -6027,14 +6032,14 @@ public @interface MovieQualifier {
Thus far most of the examples within this chapter have used XML for
specifying the configuration metadata that produces each
BeanDefinition within the Spring container.
- The previous section ()
+ The previous section ()
demonstrated the possibility of providing a considerable amount of the
configuration metadata using source-level annotations. Even in those
examples however, the "base" bean definitions were explicitly defined in
the XML file while the annotations were driving the dependency injection
- only. The current section introduces an option for implicitly detecting the
- candidate components by scanning the classpath and
- matching against filters.
+ only. The current section introduces an option for implicitly detecting
+ the candidate components by scanning the classpath
+ and matching against filters.
@Component and further stereotype
@@ -6046,7 +6051,7 @@ public @interface MovieQualifier {
stereotype of a repository (a.k.a. Data Access
Object or DAO). Among the possibilities for leveraging such a marker is
the automatic translation of exceptions as described in .
+ linkend="orm-jpa-exceptions" />.
Spring 2.5 introduces further stereotype annotations:
@Component,
@@ -6064,15 +6069,16 @@ public @interface MovieQualifier {
annotating them with @Repository,
@Service, or
@Controller instead, your classes are
- more properly suited for processing by tools or associating with aspects.
- For example, these stereotype annotations make ideal targets for
- pointcuts. Of course, it is also possible that
+ more properly suited for processing by tools or associating with
+ aspects. For example, these stereotype annotations make ideal targets
+ for pointcuts. Of course, it is also possible that
@Repository,
@Service, and
@Controller may carry additional
- semantics in future releases of the Spring Framework. Thus, if you are
- making a decision between using @Component
- or @Service for your service layer,
+ semantics in future releases of the Spring Framework. Thus, if you are
+ making a decision between using
+ @Component or
+ @Service for your service layer,
@Service is clearly the better choice.
Similarly, as stated above, @Repository
is already supported as a marker for automatic exception translation in
@@ -6088,7 +6094,7 @@ public @interface MovieQualifier {
ApplicationContext. For example, the
following two classes are eligible for such autodetection:
- @Service
+
+}]]>@Repository
public class JpaMovieFinder implements MovieFinder {
@@ -6110,24 +6116,24 @@ public class JpaMovieFinder implements MovieFinder {
alternatively a comma-separated list could be specified that included
the parent package of each class).
- <?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans"
+
+
- <context:component-scan base-package="org.example"/>
+
-</beans>
+]]>
- Note that the scanning of classpath packages requires
- the presence of corresponding directory entries in the classpath.
- When building jars with Ant, make sure to not
- activate the files-only switch of the jar task!
+ Note that the scanning of classpath packages requires the
+ presence of corresponding directory entries in the classpath. When
+ building jars with Ant, make sure to not activate
+ the files-only switch of the jar task!Furthermore, the
@@ -6153,55 +6159,82 @@ public class JpaMovieFinder implements MovieFinder {
@Repository,
@Service, or
@Controller (or classes annotated with a
- custom annotation that itself is annotated with
+ custom annotation that itself is annotated with
@Component) are the only detected
candidate components. However it is simple to modify and extend this
behavior by applying custom filters. These can be added as either
include-filter or
- exclude-filter sub-elements of the
- 'component-scan' element. Each filter element requires
- the 'type' and 'expression'
- attributes. Five filtering options exist as described below.
+ exclude-filter sub-elements of the
+ 'component-scan' element. Each filter element
+ requires the 'type' and
+ 'expression' attributes. Five filtering options exist
+ as described below.
Filter Types
-
-
-
+
+
+
+
+
+
Filter Type
+
Example Expression
+
Description
+
annotation
+
org.example.SomeAnnotation
- An annotation to be present at the type level in target components.
+
+ An annotation to be present at the type level in target
+ components.
+
assignable
+
org.example.SomeClass
- A class (or interface) that the target components are assignable to (extend/implement).
+
+ A class (or interface) that the target components are
+ assignable to (extend/implement).
+
aspectj
+
org.example..*Service+
- An AspectJ type expression to be matched by the target components.
+
+ An AspectJ type expression to be matched by the target
+ components.
+
regex
+
org\.example\.Default.*
- A regex expression to be matched by the target components' class names.
+
+ A regex expression to be matched by the target
+ components' class names.
+
custom
+
org.example.MyCustomTypeFilter
- A custom implementation of the org.springframework.core.type.TypeFilter interface.
+
+ A custom implementation of the
+ org.springframework.core.type.TypeFilter
+ interface.
@@ -6211,14 +6244,14 @@ public class JpaMovieFinder implements MovieFinder {
@Repository annotations and using "stub"
repositories instead.
- <beans ...>
+
- <context:component-scan base-package="org.example">
- <context:include-filter type="regex" expression=".*Stub.*Repository"/>
- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
- </context:component-scan>
+
+
+
+
-</beans>
+]]>It is also possible to disable the default filters by providing
@@ -6245,11 +6278,11 @@ public class JpaMovieFinder implements MovieFinder {
@Controller) that contains a
name value will thereby provide that name to the
corresponding bean definition. If such an annotation contains no
- name value or for any other detected component (such as
- those discovered due to custom filters), the default bean name generator
- will return the uncapitalized non-qualified class name. For example, if
- the following two components were detected, the names would be
- 'myMovieLister' and 'movieFinderImpl':
+ name value or for any other detected component (such
+ as those discovered due to custom filters), the default bean name
+ generator will return the uncapitalized non-qualified class name. For
+ example, if the following two components were detected, the names would
+ be 'myMovieLister' and 'movieFinderImpl':
@Service("myMovieLister")
public class SimpleMovieLister {
@@ -6271,12 +6304,12 @@ public class MovieFinderImpl implements MovieFinder {
scanner:
- <beans ...>
+
- <context:component-scan base-package="org.example"
- name-generator="org.example.MyNameGenerator" />
+
-</beans>
+]]>As a general rule, consider specifying the name with the
annotation whenever other components may be making explicit references
@@ -6309,47 +6342,47 @@ public class MovieFinderImpl implements MovieFinder {
scanner:
- <beans ...>
+
- <context:component-scan base-package="org.example"
- scope-resolver="org.example.MyScopeResolver" />
+
-</beans>
+]]>When using certain non-singleton scopes, it may be necessary to
generate proxies for the scoped objects. The reasoning is described in
detail within the section entitled . For this purpose, a
+ linkend="beans-factory-scopes-other-injection" />. For this purpose, a
scoped-proxy attribute is available on the
'component-scan' element. The three possible values are: 'no',
'interfaces', and 'targetClass'. For example, the following
configuration will result in standard JDK dynamic proxies:
- <beans ...>
+
- <context:component-scan base-package="org.example"
- scoped-proxy="interfaces" />
+
-</beans>
+]]>Providing qualifier metadata with annotationsThe @Qualifier annotation was
- introduced in the section above entitled
- . The
- examples in that section demonstrated use of the
- @Qualifier annotation as well
- as custom qualifier annotations to provide fine-grained control
- when resolving autowire candidates. Since those examples were
- based on XML bean definitions, the qualifier metadata was provided
- on the candidate bean definitions using the 'qualifier'
- or 'meta' sub-elements of the 'bean'
- element in the XML. When relying upon classpath scanning for
- autodetection of components, then the qualifier metadata may
- be provided with type-level annotations on the candidate class.
- The following three examples demonstrate this technique.
+ introduced in the section above entitled . The examples in that
+ section demonstrated use of the
+ @Qualifier annotation as well as custom
+ qualifier annotations to provide fine-grained control when resolving
+ autowire candidates. Since those examples were based on XML bean
+ definitions, the qualifier metadata was provided on the candidate bean
+ definitions using the 'qualifier' or
+ 'meta' sub-elements of the 'bean'
+ element in the XML. When relying upon classpath scanning for
+ autodetection of components, then the qualifier metadata may be provided
+ with type-level annotations on the candidate class. The following three
+ examples demonstrate this technique.
@Component
@Qualifier("Action")
@@ -6369,12 +6402,14 @@ public class CachingMovieCatalog implements MovieCatalog {
// ...
}
- As with most of the annotation-based alternatives, keep
- in mind that the annotation metadata is bound to the class
- definition itself, while the use of XML allows for multiple
- beans of the same type to provide variations
- in their qualifier metadata since that metadata is provided
- per-instance rather than per-class.
+
+ As with most of the annotation-based alternatives, keep in mind
+ that the annotation metadata is bound to the class definition itself,
+ while the use of XML allows for multiple beans of the same
+ type to provide variations in their qualifier metadata
+ since that metadata is provided per-instance rather than
+ per-class.
+
@@ -6384,11 +6419,11 @@ public class CachingMovieCatalog implements MovieCatalog {
The context namespace introduced in Spring 2.5
provides a load-time-weaver element.
- <beans ...>
+
- <context:load-time-weaver/>
+
-</beans>
+]]>Adding this element to an XML-based Spring configuration file
activates a Spring LoadTimeWeaver for the
@@ -6400,6 +6435,6 @@ public class CachingMovieCatalog implements MovieCatalog {
load-time weaving may be necessary for JPA class transformation. Consult
the LocalContainerEntityManagerFactoryBean Javadoc
for more detail. For more on AspectJ load-time weaving, see .
+ linkend="aop-aj-ltw" />.
\ No newline at end of file
diff --git a/spring-framework-reference/src/resources.xml b/spring-framework-reference/src/resources.xml
index 79f49734491..abedb987956 100644
--- a/spring-framework-reference/src/resources.xml
+++ b/spring-framework-reference/src/resources.xml
@@ -27,7 +27,7 @@
to be a more capable interface for abstracting access to low-level
resources.
-
-
@@ -244,7 +244,7 @@
to be implemented by objects that can return (i.e. load)
Resource instances.
- public interface ResourceLoader {
+ public interface ResourceLoader {
Resource getResource(String location);
}
@@ -261,7 +261,7 @@
of code was executed against a
ClassPathXmlApplicationContext instance:
- Resource template = ctx.getResource("some/resource/path/myTemplate.txt);
+ Resource template = ctx.getResource("some/resource/path/myTemplate.txt);What would be returned would be a
ClassPathResource; if the same method was executed
@@ -278,15 +278,15 @@
application context type, by specifying the special
classpath: prefix:
- Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt);
+ Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt);Similarly, one can force a UrlResource to be
used by specifying any of the standard java.net.URL
prefixes:
- Resource template = ctx.getResource("file:/some/resource/path/myTemplate.txt);
+ Resource template = ctx.getResource("file:/some/resource/path/myTemplate.txt);
- Resource template = ctx.getResource("http://myhost.com/resource/path/myTemplate.txt);
+ Resource template = ctx.getResource("http://myhost.com/resource/path/myTemplate.txt);The following table summarizes the strategy for converting
Strings to
@@ -361,7 +361,7 @@
a special marker interface, identifying objects that expect to be provided
with a ResourceLoader reference.
-
@@ -427,7 +427,7 @@
Resource, it can be configured with a
simple string for that resource, as follows:
-
+
]]>
@@ -446,9 +446,9 @@
UrlResource (the latter being used to access a
filesystem file).
- ]]>
+ ]]>
- ]]>
+ ]]>
@@ -468,7 +468,7 @@
specific application context. For example, if you create a
ClassPathXmlApplicationContext as follows:
-
+ The bean definitions will be loaded from the classpath, as a
ClassPathResource will be
@@ -476,7 +476,7 @@
FileSystemXmlApplicationContext as
follows:
- The bean definition will be loaded from a filesystem location, in
@@ -487,7 +487,7 @@
Resource created to load the definition.
So this FileSystemXmlApplicationContext...
- ... will actually load its bean definitions from the classpath.
@@ -521,7 +521,7 @@
and 'daos.xml' could be instantiated like
so...
- Please do consult the Javadocs for the
@@ -617,7 +617,7 @@
string may use the special classpath*:
prefix:
- This special prefix specifies that all classpath resources that
@@ -706,19 +706,19 @@
all location paths as relative, whether they start with a leading slash
or not. In practice, this means the following are equivalent:
-
- As are the following: (Even though it would make sense for them to
be different, as one case is relative and the other absolute.)
-
- In practice, if true absolute filesystem paths are needed, it is
@@ -728,10 +728,10 @@ ctx.getResource("/some/resource/path/myTemplate.txt");]]>
the use of a UrlResource, by using the
file: URL prefix.
- // actual context type doesn't matter, the Resource will always be UrlResource// actual context type doesn't matter, the Resource will always be UrlResource
- // force this FileSystemXmlApplicationContext to load its definition via a UrlResource// force this FileSystemXmlApplicationContext to load its definition via a UrlResource
diff --git a/spring-framework-reference/src/testing.xml b/spring-framework-reference/src/testing.xml
index c5688912c15..3520aab8390 100644
--- a/spring-framework-reference/src/testing.xml
+++ b/spring-framework-reference/src/testing.xml
@@ -468,7 +468,7 @@
the test will be enabled. This annotation can be applied to an
entire class or individual methods.
- @IfProfileValue(name="java.vendor", value="Sun Microsystems Inc.")
+ @IfProfileValue(name="java.vendor", value="Sun Microsystems Inc.")
public void testProcessWhichRunsOnlyOnSunJvm() {
// some logic that should run only on Java VMs from Sun Microsystems
}
@@ -479,7 +479,7 @@ public void testProcessWhichRunsOnlyOnSunJvm() {
for test groups in a JUnit environment.
Consider the following example:
- @IfProfileValue(name="test-groups", values={"unit-tests", "integration-tests"})
+ @IfProfileValue(name="test-groups", values={"unit-tests", "integration-tests"})
public void testProcessWhichRunsForUnitOrIntegrationTestGroups() {
// some logic that should run only for unit and integration test groups
}
@@ -498,7 +498,7 @@ public void testProcessWhichRunsForUnitOrIntegrationTestGroups() {
SystemProfileValueSource will be used by
default.
- @ProfileValueSourceConfiguration(CustomProfileValueSource.class)
+ @ProfileValueSourceConfiguration(CustomProfileValueSource.class)
public class CustomProfileValueSourceTests {
// class body...
}
@@ -514,7 +514,7 @@ public class CustomProfileValueSourceTests {
test method finishes execution (regardless of whether the test
passed or not).
- @DirtiesContext
+ @DirtiesContext
public void testProcessWhichDirtiesAppCtx() {
// some logic that results in the Spring container being dirtied
}
@@ -531,7 +531,7 @@ public void testProcessWhichDirtiesAppCtx() {
Likewise if an instance of the exception is not
thrown during the test method execution then the test fails.
- @ExpectedException(SomeBusinessException.class)
+ @ExpectedException(SomeBusinessException.class)
public void testProcessRainyDayScenario() {
// some logic that should result in an Exception being thrown
}
@@ -552,7 +552,7 @@ public void testProcessRainyDayScenario() {
set up or tear down of the
test fixture.
- @Timed(millis=1000)
+ @Timed(millis=1000)
public void testProcessWithOneSecondTimeout() {
// some logic that should not take longer than 1 second to execute
}
@@ -571,7 +571,7 @@ public void testProcessWithOneSecondTimeout() {
up or tear down of the test
fixture.
- @Repeat(10)
+ @Repeat(10)
public void testProcessRepeatedly() {
// ...
}
@@ -588,7 +588,7 @@ public void testProcessRepeatedly() {
committed. Use @Rollback to override
the default rollback flag configured at the class level.
- @Rollback(false)
+ @Rollback(false)
public void testProcessWithoutRollback() {
// ...
}
@@ -602,7 +602,7 @@ public void testProcessWithoutRollback() {
test method must not execute in a transactional
context.
- @NotTransactional
+ @NotTransactional
public void testProcessWithoutTransaction() {
// ...
}
@@ -659,7 +659,7 @@ public void testProcessWithoutTransaction() {
and exposes a protected method that subclasses can
override to provide the location of context definition files:
- protected String[] getConfigLocations()
+ protected String[] getConfigLocations()Implementations of this method must provide an array containing
the resource locations of XML configuration metadata - typically on
@@ -669,9 +669,9 @@ public void testProcessWithoutTransaction() {
configuration. As an alternative you may choose to override one of the
following. See the respective JavaDoc for further details.
- protected String[] getConfigPaths()
+ protected String[] getConfigPaths()
- protected String getConfigPath()
+ protected String getConfigPath()By default, once loaded, the configuration file set will be
reused for each test case. Thus the setup cost will be incurred only
@@ -710,7 +710,7 @@ public void testProcessWithoutTransaction() {
at a JUnit 3.8 based implementation of the test class itself (we will
look at the configuration immediately afterwards).
- public final class HibernateTitleDaoTests public final class HibernateTitleDaoTests extends AbstractDependencyInjectionSpringContextTests {
// this instance will be (automatically) dependency injected
@@ -738,7 +738,7 @@ public void testProcessWithoutTransaction() {
"classpath:com/foo/daos.xml") looks like
this:
- <?xml version="1.0" encoding="UTF-8"?>
+ <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
@@ -785,7 +785,7 @@ public void testProcessWithoutTransaction() {
configuration does not need to change, merely the test
fixture).
- public final class HibernateTitleDaoTests public final class HibernateTitleDaoTests extends AbstractDependencyInjectionSpringContextTests {
public HibernateTitleDaoTests() {
@@ -1096,7 +1096,7 @@ public void testProcessWithoutTransaction() {
application context from
"classpath:/com/example/MyTest-context.xml".
- package com.example;
+ package com.example;
@RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from "classpath:/com/example/MyTest-context.xml"
@@ -1118,7 +1118,7 @@ public class MyTest {
configure your own custom
ContextLoader.
- @RunWith(SpringJUnit4ClassRunner.class)
+ @RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from "/applicationContext.xml" and "/applicationContext-test.xml"// in the root of the classpath@ContextConfiguration(locations={"/applicationContext.xml", "/applicationContext-test.xml"})
@@ -1144,7 +1144,7 @@ public class MyTest {
"/extended-context.xml" may therefore override those defined in
"/base-context.xml".
- @RunWith(SpringJUnit4ClassRunner.class)
+ @RunWith(SpringJUnit4ClassRunner.class)
// ApplicationContext will be loaded from "/base-context.xml" in the root of the classpath@ContextConfiguration(locations={"/base-context.xml"})
public class BaseTest {
@@ -1245,7 +1245,7 @@ public class ExtendedTest extends BaseTest {
JUnit 4.4. The same DI techniques can be used in conjunction with any
testing framework.
- @RunWith(SpringJUnit4ClassRunner.class)
+ @RunWith(SpringJUnit4ClassRunner.class)
// specifies the Spring configuration to load for this test fixture@ContextConfiguration(locations={"daos.xml"})
public final class HibernateTitleDaoTests {
@@ -1266,7 +1266,7 @@ public final class HibernateTitleDaoTests {
Alternatively, we can configure the class to use
@Autowired for setter injection.
- @RunWith(SpringJUnit4ClassRunner.class)
+ @RunWith(SpringJUnit4ClassRunner.class)
// specifies the Spring configuration to load for this test fixture@ContextConfiguration(locations={"daos.xml"})
public final class HibernateTitleDaoTests {
@@ -1291,7 +1291,7 @@ public final class HibernateTitleDaoTests {
Now let's take a look at an example using
@Resource for field injection.
- @RunWith(SpringJUnit4ClassRunner.class)
+ @RunWith(SpringJUnit4ClassRunner.class)
// specifies the Spring configuration to load for this test fixture@ContextConfiguration(locations={"daos.xml"})
public final class HibernateTitleDaoTests {
@@ -1312,7 +1312,7 @@ public final class HibernateTitleDaoTests {
Finally, here is an example using
@Resource for setter injection.
- @RunWith(SpringJUnit4ClassRunner.class)
+ @RunWith(SpringJUnit4ClassRunner.class)
// specifies the Spring configuration to load for this test fixture@ContextConfiguration(locations={"daos.xml"})
public final class HibernateTitleDaoTests {
@@ -1338,7 +1338,7 @@ public final class HibernateTitleDaoTests {
by the @ContextConfiguration annotation
(i.e., "daos.xml") which looks like this:
- <?xml version="1.0" encoding="UTF-8"?>
+ <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
@@ -1364,7 +1364,7 @@ public final class HibernateTitleDaoTests {
you may override the setter and use the @Qualifier
annotation to indicate a specific target bean as follows:
- ...
+ ...
@Override @Autowired
public void setDataSource(@Qualifier("myDataSource") DataSource dataSource) {
super.setDataSource(dataSource);
@@ -1389,7 +1389,7 @@ public final class HibernateTitleDaoTests {
Note that this always points to a bean with that specific name,
no matter whether there is one or more beans of the given type.
- ...
+ ...
@Override @Resource("myDataSource")
public void setDataSource(DataSource dataSource) {
super.setDataSource(dataSource);
@@ -1479,7 +1479,7 @@ public final class HibernateTitleDaoTests {
support section of the reference manual for further information
and configuration examples.
- @RunWith(SpringJUnit4ClassRunner.class)
+ @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TransactionConfiguration(transactionManager="txMgr", defaultRollback=false)@Transactional
@@ -1695,7 +1695,7 @@ public class FictitiousTransactionalTest {
ApplicationContext be configured via
@ContextConfiguration.
- @RunWith(SpringJUnit4ClassRunner.class)
+ @RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({})
public class SimpleTest {
@@ -1913,7 +1913,7 @@ public class SimpleTest {
ContextLoader strategy to use for
loading the context.
- @ContextConfiguration(locations={"example/test-context.xml"}, loader=CustomContextLoader.class)
+ @ContextConfiguration(locations={"example/test-context.xml"}, loader=CustomContextLoader.class)
public class CustomConfiguredApplicationContextTests {
// class body...
}
@@ -1937,7 +1937,7 @@ public class CustomConfiguredApplicationContextTests {
will be used in conjunction with
@ContextConfiguration.
- @ContextConfiguration
+ @ContextConfiguration
@TestExecutionListeners({CustomTestExecutionListener.class, AnotherTestExecutionListener.class})
public class CustomTestExecutionListenerTests {
// class body...
@@ -1965,7 +1965,7 @@ public class CustomTestExecutionListenerTests {
used in conjunction with
@ContextConfiguration.
- @ContextConfiguration
+ @ContextConfiguration
@TransactionConfiguration(transactionManager="txMgr", defaultRollback=false)
public class CustomConfiguredTransactionalTests {
// class body...
@@ -1982,7 +1982,7 @@ public class CustomConfiguredTransactionalTests {
transaction via the @Transactional
annotation.
- @BeforeTransaction
+ @BeforeTransaction
public void beforeTransaction() {
// logic to be executed before a transaction is started
}
@@ -1998,7 +1998,7 @@ public void beforeTransaction() {
transaction via the @Transactional
annotation.
- @AfterTransaction
+ @AfterTransaction
public void afterTransaction() {
// logic to be executed after a transaction has ended
}
@@ -2019,7 +2019,7 @@ public void afterTransaction() {
AbstractClinicTests, for which a partial listing
is shown below:
- @ContextConfiguration
+ @ContextConfiguration
public abstract class AbstractClinicTests extends AbstractTransactionalJUnit4SpringContextTests {
@Autowired
@@ -2106,7 +2106,7 @@ public abstract class AbstractClinicTests extends Abstract
overriding beans defined in
"AbstractClinicTests-context.xml".
- @ContextConfiguration
+ @ContextConfiguration
public class HibernateClinicTests extends AbstractClinicTests { }
diff --git a/spring-framework-reference/src/validation.xml b/spring-framework-reference/src/validation.xml
index 86ef41432b3..032d059b82d 100644
--- a/spring-framework-reference/src/validation.xml
+++ b/spring-framework-reference/src/validation.xml
@@ -43,7 +43,7 @@
an Errors object so that while validating, validators can report
validation failures to the Errors object.
Let's consider a small data object:
- Validator is fairly straightforward,
especially when you know of the ValidationUtils helper class
that the Spring Framework also provides.
- /**
* This Validator validates justPerson instances
@@ -109,7 +109,7 @@ public class Person {
AddressValidator class without recourse to copy-n-paste you can
dependency-inject or instantiate an AddressValidator within your
CustomerValidator, and use it like so:
- PropertyEditors.)Consider the following two classes:
-
- The following code snippets show some examples of how to retrieve
and manipulate some of the properties of instantiated
Companies and Employees:
- // setting the company name..// ... can also be done like this:
would associate a CustomNumberEditor with the age
property of the Foo class.
- Consider a user class ExoticType, and another class
DependsOnExoticType which needs ExoticType set as a property:
- When things are properly set up, we want to be able to assign the type property as a string, which a
PropertyEditor will behind the scenes convert into an actual
ExoticType instance:
-
+
]]>The PropertyEditor implementation could look similar to this:
- // converts string representation to ExoticType object// converts string representation to ExoticType objectFinally, we use CustomEditorConfigurer to register the new
PropertyEditor with the ApplicationContext,
which will then be able to use it as needed:
-
+